Tsql操作数类型冲突:日期与int不兼容

时间:2017-08-21 10:21:56

标签: sql-server

使用此代码我收到此错误:

  

"操作数类型冲突:日期与int"

不兼容
declare
    @StrSql nvarchar(max),
    @TableName nvarchar(50),
    @Month datetime
set
    @TableName = 'dbo.OneTransfer'
set
    @month ='2016-02-02'
set
    @StrSql ='select * from ' + @TableName + ' where OperateDate >=' + CONVERT(char(10),@Month,20)
execute (@StrSql)

这是我的SQL表:

enter image description here

1 个答案:

答案 0 :(得分:2)

这是您的错误:

set @StrSql ='select * from ' + @TableName + ' where OperateDate >=' + CONVERT(char(10),@Month,20)

尝试将其打印出来,它会显示UNQUOTED日期字符串

where OperateDate >= 2016-02-02

因此导致错误OperateDate >= 2016

您需要的是QUOTEyour日期字符串:

set @StrSql ='select * from ' + @TableName + ' where OperateDate >=' + quotename(CONVERT(char(10),@Month,20), '''')