【发布时间】:2010-10-17 00:57:29
【问题描述】:
考虑以下 TSQL:
SET @WhereClause1 = 'where a.Date > ' + @InvoiceDate
我收到日期/字符串转换错误。 @InvoiceDate 是一个日期时间变量。什么是正确的语法?
【问题讨论】:
标签: tsql datetime date dynamic-sql
考虑以下 TSQL:
SET @WhereClause1 = 'where a.Date > ' + @InvoiceDate
我收到日期/字符串转换错误。 @InvoiceDate 是一个日期时间变量。什么是正确的语法?
【问题讨论】:
标签: tsql datetime date dynamic-sql
这可能有效。
SET @WhereClause1 = 'where a.Date > ''' + convert(varchar, @InvoiceDate) + ''''
虽然如果值为 null 会引发错误。
【讨论】:
这将起作用:
SET @WhereClause1 = 'where a.Date > ''' + cast(@InvoiceDate as varchar(100)) + ''''
【讨论】:
由于您首先将查询组合为字符串,因此我认为您需要将@InvoiceDate 转换为具有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
【讨论】:
...您可能需要将日期字符串括在引号中。
在调用例程中构造日期字符串实际上可能会更好,因为您应该在那里检查空值和其他验证。
【讨论】:
EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > @date',
N'@date datetime',
@date = @InvoiceDate
【讨论】: