views:

843

answers:

5

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?

+1  A: 

This might work.

SET @WhereClause1 = 'where a.Date > ''' + convert(varchar, @InvoiceDate) + ''''
Andy White
this doesn't work because you have to enclosed the date (inside the string) with quotation marks
eKek0
Ok, thanks, I'll fix it
Andy White
with the '' correction this did what I needed. thanks all
Jeff
+1  A: 

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

AaronLS
+1  A: 

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

le dorfier
+4  A: 

This will work:

SET @WhereClause1 = 'where a.Date > ''' + cast(@InvoiceDate as varchar(100)) + ''''
eKek0
i wish I could mark two answers approved because this one works too. thanks
Jeff
+1 for getting it 100% right
Andy White
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 :)
eKek0
A: 
EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > @date',
                   N'@date datetime',
                   @date = @InvoiceDate
Anthony Faull