【问题标题】:Tsql Operand type clash: date is incompatible with intTsql 操作数类型冲突:日期与 int 不兼容
【发布时间】:2017-08-21 10:21:55
【问题描述】:

使用这段代码我得到了这个错误:

“操作数类型冲突:日期与 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 表:

【问题讨论】:

  • 不要写这样的代码。使用参数化查询。连接字符串会使您面临 SQL 注入攻击,像这样的转换错误 会阻止您传递 Unicode 数据——比如汉字。使用select * from my table where OperateDate>=@date并使用`sp_executesql传递日期参数

标签: sql-server


【解决方案1】:

这是你的错误:

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

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

where OperateDate >= 2016-02-02

所以是OperateDate >= 2016 导致错误。

你需要的是引用你的日期字符串:

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

【讨论】:

  • 感谢您的宝贵时间。这是工作。非常清楚。我真的很感激。
猜你喜欢
  • 2019-10-31
  • 2016-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 2021-09-24
相关资源
最近更新 更多