我正在尝试使用日期过滤器批量更新数据。
below is my sample table[myTable] data:
+--------+------------+-----------+
| ID | Amount | ResetDay |
+--------+------------+-----------+
| 1 | 100 | 1 |
+--------+------------+-----------+
| 2 | 100 | 2 |
+--------+------------+-----------+
| 3 | 100 | 29 |
+--------+------------+-----------+
| 4 | 100 | 30 |
+--------+------------+-----------+
这是我的查询:
update myTable set Amount = 0
where ID in (case when ResetDay > day(eomonth(getdate()))
then (select ID from myTable where ResetDay > day(eomonth(getdate())))
else (select ID from myTable where ResetDay = day(getdate()))) end)
我有带有日期触发器的自动批处理更新。我使用的条件是,当ResetDay
大于月末时,它将更新具有更大的ResetDay
的所有数据。否则,它将仅更新等于日期的数据。
样本查询和预期输出: 查询:(这是针对月底日小于ResetDay的示例)
update myTable set Amount = 0
where ID in (case when ResetDay > 28
then (select ID from myTable where ResetDay > 28)
else (select ID from myTable where ResetDay = 1) end)
Output:
+--------+------------+-----------+
| ID | Amount | ResetDay |
+--------+------------+-----------+
| 1 | 100 | 1 |
+--------+------------+-----------+
| 2 | 100 | 2 |
+--------+------------+-----------+
| 3 | 0 | 29 |
+--------+------------+-----------+
| 4 | 0 | 30 |
+--------+------------+-----------+
如何限制SQL Server的条件?当我运行这些查询Subquery returned more than 1 value, This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
答案 0 :(得分:3)
您的查询本质上是一个自我联接。根本不需要,但这似乎是在不需要时尝试使用CASE
的结果。
相同查询可以重写为:
update myTable
set Amount = 0
where (ResetDay > day(eomonth(getdate())) and ResetDay > day(eomonth(getdate())))
OR (ResetDay <= day(eomonth(getdate())) and ResetDay = day(getdate())))
我什至在这里都不打算计算括号,这些公式不应该出现在查询中。一种更简洁的写法是:
declare @eomday int=day(eomonth(getdate())), @today int =day(getdate());
update myTable
set Amount = 0
where (ResetDay > @eomday and ResetDay > @eomday)
OR (ResetDay <= @eomday and ResetDay = @today)
很明显条件不正确。第一对是重复项,而第二对则只相当于ResetDay=@today
,因为当前月份的日期总是大于或等于今天。
查询可以重写为:
update myTable
set Amount = 0
where ResetDay > @eomday
OR ResetDay = @today
该查询说的是您的要求所说的话:
当ResetDay大于月末时,它将更新具有更大ResetDay的所有数据。否则,它将仅更新等于日期的数据。