TSQL -- Inserting Dates Into Dynamic SQL
Asked Answered
P

5

7

Consider the following TSQL:

SET @WhereClause1 = 'where a.Date > ' + @InvoiceDate

I get a date/string conversion error. @InvoiceDate is a datetime variable. What is the right syntax?

Pulley answered 2/4, 2009 at 5:2 Comment(0)
S
8

This might work.

SET @WhereClause1 = 'where a.Date > ''' + convert(varchar, @InvoiceDate) + ''''

although an error will be raised if the value is null.

Scotopia answered 2/4, 2009 at 5:4 Comment(1)
this doesn't work because you have to enclosed the date (inside the string) with quotation marksTatman
T
6

This will work:

SET @WhereClause1 = 'where a.Date > ''' + cast(@InvoiceDate as varchar(100)) + ''''
Tatman answered 2/4, 2009 at 5:11 Comment(2)
i wish I could mark two answers approved because this one works too. thanksPulley
When I have that trouble, I select one and give points (arrow up) to the others (if they are more than 1). That doesn't mean you have to do the same :)Tatman
A
1

Since your composing query as a string first, then I think you need to convert @InvoiceDate to a string with something like this. http://www.databasejournal.com/features/mssql/article.php/10894_2197931_1/Working-with-SQL-Server-DateTime-Variables-Part-Two---Displaying-Dates-and-Times-in-Different-Formats.htm

Australia answered 2/4, 2009 at 5:5 Comment(0)
K
1

... and you will probably need to enclose date strings in quotes.

It would probably actually be better to construct the date string in the calling routine because you should be checking there for null values and maybe other validations.

Kiaochow answered 2/4, 2009 at 5:7 Comment(0)
A
1
EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > @date',
                   N'@date datetime',
                   @date = @InvoiceDate
Aspergillosis answered 26/4, 2010 at 19:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.