更新查询失败“0”行受影响

Update query failed '0' rows affected

我正在尝试 运行 这个查询,但查询一直放弃我:

Update StockInvoiceInfo set Quantity = Quantity - 2  where p_id = 5 AND ProductDate = convert(Cast('31-5-2015' as datetime)) ;

在 运行 这段代码之后 returns 下面是一个错误:

Incorrect syntax near '31-5-2015'

ProductDate 列的数据类型是Date。我正在使用 Sql Server 2012.

您使用了 Convert 函数但没有为其提供参数。这里也不需要这个功能。还要注意日期格式。我已将其更改为标准格式:

Update StockInvoiceInfo set Quantity = Quantity - 2  
where p_id = 5 AND ProductDate = Cast('2015-05-31' as datetime)

使用CAST('5-31-2015' as DATETIME)

使用上述更新语句开始转换,但语法不完整 这里的转换语法

  Update StockInvoiceInfo 
set Quantity = Quantity - 2  
where p_id = 5
 AND ProductDate = convert(datetime,Cast('31-5-2015' as varchar),103) ;

如果您只想比较 Sql 日期,那么只需使用像 '20150531' 或更易于阅读的不可知格式 '2015-05-31'。根本不需要转换或转换,即

WHERE ... AND ProductDate = '2015-05-31'

但是,如果 ProductDate 不是日期,而是 *DATETIME* 数据类型之一,并且您希望在同一天的任何时间更新,那么我相信您正在寻找对于类似的东西:

Update StockInvoiceInfo 
set Quantity = Quantity - 2  
where 
  p_id = 5 
  AND CAST(ProductDate AS DATE) = '2015-05-31';

但是,性能会很差,因为该子句不太可能是 SARGable。你最好简单地做:

AND ProductDate >= '2015-05-31' AND ProductDate < '2015-06-01';

(抵制使用 between 的诱惑,或者像 ':23:59:59' 这样的 hack,因为会有数据角落案例会咬你)