7

考虑以下 TSQL:

SET @WhereClause1 = 'where a.Date > ' + @InvoiceDate

我收到日期/字符串转换错误。 @InvoiceDate是一个日期时间变量。什么是正确的语法?

4

5 回答 5

8

这可能会奏效。

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

尽管如果值为 null 则会引发错误。

于 2009-04-02T05:04:40.310 回答
6

这将起作用:

SET @WhereClause1 = 'where a.Date > ''' + cast(@InvoiceDate as varchar(100)) + ''''
于 2009-04-02T05:11:43.697 回答
1

由于您首先将查询编写为字符串,因此我认为您需要将 @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-格式.htm

于 2009-04-02T05:05:30.950 回答
1

...并且您可能需要将日期字符串括在引号中。

在调用例程中构造日期字符串实际上可能会更好,因为您应该在那里检查空值和其他验证。

于 2009-04-02T05:07:33.237 回答
1
EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > @date',
                   N'@date datetime',
                   @date = @InvoiceDate
于 2010-04-26T19:32:37.063 回答