Question

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?

Was it helpful?

Solution

This might work.

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

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

OTHER TIPS

This will work:

SET @WhereClause1 = 'where a.Date > ''' + cast(@InvoiceDate as varchar(100)) + ''''

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

... 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.

EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > @date',
                   N'@date datetime',
                   @date = @InvoiceDate
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top