我正在使用ms-sql server。我table
update
select statement
Table_A
。例如,我要更新的表格为2 rows
,其中包含10 rows
。我想要更新Table_A的更新语句返回update Table_A 10 times
。所以我想updated 2 times
。问题是Table_A是the count of rows in Table_A
(CREATE TABLE #tmp
(
AccountID INT,
Inflow DECIMAL(10,2)
)
DECLARE @n INT = 0
WHILE (@n <10 )
BEGIN
INSERT INTO #tmp SELECT 2, 10
SET @n += 1
END
UPDATE dbo.Table_A
SET Balance += sss.Inflow
FROM ( SELECT t.AccountID ,
t.Inflow
FROM #tmp AS t
) AS sss
WHERE dbo.tAccount.AccountID = sss.AccountID;
-- Updates only 2 times
-- What I expected here is Table_A to be updated as many times as the count of the select statement which is 10, based on the insert before.
)。
示例:
numberArray.map(n=>stringArray[n-1])
答案 0 :(得分:2)
你的期望是错误的。不可否认,documentation掩盖了这个想法:
示例运行时没有错误,但每个
SalesYTD
值都会更新 只有一次销售,无论实际发生了多少次销售 那天。 这是因为单个UPDATE
语句永远不会更新 同一行两次。
文档继续解决方案:
在指定的多个销售的情况下 销售人员可以在同一天发生,每个销售的所有销售 必须在
UPDATE
声明中将人聚集在一起 如下例所示:
因此,在执行join
之前简单地聚合:
UPDATE dbo.Table_A
SET Balance += sss.Inflow
FROM (SELECT t.AccountID, SUM(t.Inflow) as Inflow
FROM #tmp t
GROUP BY t.AccountId
) sss
WHERE dbo.tAccount.AccountID = sss.AccountID;
请注意,您也可以将其写为:
UPDATE a
SET Balance += sss.Inflow
FROM dbo.Table_A a JOIN
(SELECT t.AccountID, SUM(t.Inflow) as Inflow
FROM #tmp t
GROUP BY t.AccountId
) sss
ON a.AccountID = sss.AccountID;
这使JOIN
更明确。