这应该是一个简单的UPDATE
,我认为应该在两个不同的列上两次更新相同的记录,但它不起作用。
简化的示例代码:
DECLARE @nowWithDate DATETIME = GETDATE()
DECLARE @result TABLE(Id INT, Poll1Date DATETIME, Poll2Date DATETIME)
INSERT INTO @result VALUES(1, NULL, NULL)
;WITH data(Id, IsPoll1, IsPoll2) AS
(
SELECT 1, 1, 0
UNION ALL
SELECT 1, 0, 1
)
UPDATE r
SET Poll1Date = IIF(d.IsPoll1 = 1, @nowWithDate, Poll1Date),
Poll2Date = IIF(d.IsPoll2 = 1, @nowWithDate, Poll2Date)
FROM @result r
JOIN data d ON d.Id = r.Id
SELECT * FROM @result
我无法弄清楚,为什么第二个日期没有更新?看起来这行只更新一次。
答案 0 :(得分:1)
DECLARE @nowWithDate DATETIME = GETDATE()
DECLARE @result TABLE(Id INT, Poll1Date DATETIME, Poll2Date DATETIME)
INSERT INTO @result VALUES(1, NULL, NULL)
;WITH data(Id, IsPoll1, IsPoll2) AS
(
SELECT 1, 1, 0
UNION ALL
SELECT 1, 0, 1
)
select * from data
返回2行。因此,当您使用@results
加入时,它仅从第一行更新。对于第一行,IsPoll1 = 1但IsPoll2 = 0,因此,第二行未更新。
更新两行
DECLARE @nowWithDate DATETIME = GETDATE()
DECLARE @result TABLE(Id INT, Poll1Date DATETIME, Poll2Date DATETIME)
INSERT INTO @result VALUES(1, NULL, NULL)
;WITH data(Id, IsPoll1, IsPoll2) AS
(
select Id, SUM (IsPoll1),SUM(IsPoll2) from(
SELECT 1 as Id, 1 as IsPoll1, 0 as IsPoll2
UNION ALL
SELECT 1 as Id,0 as IsPoll1, 1 as IsPoll2) d1
group by d1.Id
)
UPDATE r
SET Poll1Date = IIF(d.IsPoll1 = 1, @nowWithDate, Poll1Date),
Poll2Date = IIF(d.IsPoll2 = 1, @nowWithDate, Poll2Date)
FROM @result r
JOIN data d ON d.Id = r.Id
SELECT * FROM @result