TSQL - 将日期插入动态SQL
-
22-08-2019 - |
题
考虑以下TSQL:
SET @WhereClause1 = 'where a.Date > ' + @InvoiceDate
我得到一个日期/字符串转换错误。 @InvoiceDate
是DateTime变量。什么是正确的语法?
解决方案
这可能起作用。
SET @WhereClause1 = 'where a.Date > ''' + convert(varchar, @InvoiceDate) + ''''
尽管该值为null,则会增加错误。
其他提示
这将起作用:
SET @WhereClause1 = 'where a.Date > ''' + cast(@InvoiceDate as varchar(100)) + ''''
由于首先将查询作为字符串,因此我认为您需要将@invoicedate转换为字符串, 这个. http://www.databasejournal.com/features/mssql/article.php/10894_2197931_1/working-with-with-sql-sql-server-datetime-variables-part-part-two---------------- formats.htm
...而且您可能需要将日期字符串包裹在报价中。
实际上,在调用例程中构造日期字符串可能会更好,因为您应该在此检查无效值以及其他验证。
EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > @date',
N'@date datetime',
@date = @InvoiceDate
不隶属于 StackOverflow