TSQL -- Inserting Dates Into Dynamic SQL

Jeff picture Jeff · Apr 2, 2009 · Viewed 11.4k times · Source

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?

Answer

Andy White picture Andy White · Apr 2, 2009

This might work.

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

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