0

Hy,

I have a problem and I can't figure it out...

    declare @start_date datetime, @date_1m datetime, @date_1m_end datetime

    set @start_date = GETDATE()
    set @date_1m = DATEADD(MONTH,-1,DATEADD(MONTH, DATEDIFF(MONTH, 0, @start_date),0))
    set @date_1m_end = DATEADD(SS, -1, DATEADD(MONTH, 1, @date_1m))

    set @sql_exec = 'insert into #temp select ... where a.date between ' + @date_1m + ' and ' + @date_1m_end + ''
exec(@sql_exec)

and it gives me the following error :

Conversion failed when converting date and/or time from character string.

Why and how to solve this because it's getting frustrating ..

PS: I need to run exec() because this stored procedure will run every month and it creates database for that month

Thanks you very much

1 Answer 1

1

TSql is trying to convert all your text to datetime. You need to convert dates to strings before concationation, and convert them back to dates in query.

set @sql_exec = 'insert into #temp select ... where a.date between ' 
    + 'convert(datetime, ''' 
    + convert(varchar(10), @date_1m, 104) 
    + ''', 104)'
    + ' and '
    + 'convert(datetime, ''' 
    + convert (varchar(10), @date_1m_end, 104) 
    + ''', 104)'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.