SQL SERVER如何更新另一个表中存在的表中的所有行
Posted
技术标签:
【中文标题】SQL SERVER如何更新另一个表中存在的表中的所有行【英文标题】:SQL SERVER How to UPDATE all rows in a table that exists in other table 【发布时间】:2017-06-20 01:29:02 【问题描述】:我有这个 UPDATE SENTENCE 更新行,如果存在对每一行进行除法,每一行都有不同的 Rate/HR
UPDATE CP_ValueStream_Data
SET
CP_ValueStream_Data.W1 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W1 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate AS FLOAT),2)),
CP_ValueStream_Data.W2 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W2 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W3 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W3 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W4 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W4 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W5 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W5 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W6 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W6 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W7 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W7 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W8 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W8 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W9 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W9 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W10 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W10 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W11 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W11 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W12 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W12 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
CP_ValueStream_Data.W13 = (SELECT ROUND(CAST((SELECT [CP_Demand_G&PS].W13 FROM [CP_Demand_G&PS]) AS FLOAT)/CAST(Rate_Hr AS FLOAT),2)),
Active = 1
FROM
[CP_Demand_G&PS]
INNER JOIN CP_ValueStream_Data
ON [CP_Demand_G&PS].RowLabels = CP_ValueStream_Data.Material
但是当我执行查询时返回一个错误
子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。
【问题讨论】:
当您已经加入表格时,您不应该在 SET 部分中使用子查询。就= ROUND(CAST([CP_Demand_G&PS].W... AS FLOAT)/...)
【参考方案1】:
您不需要子查询:
UPDATE CP_ValueStream_Data
SET CP_ValueStream_Data.W1 = ROUND(CAST(d.W1 AS FLOAT)/CAST(Rate AS FLOAT), 2),
. . .
Active = 1
FROM [CP_Demand_G&PS] d INNER JOIN
CP_ValueStream_Data v
ON d.RowLabels = v.Material;
【讨论】:
以上是关于SQL SERVER如何更新另一个表中存在的表中的所有行的主要内容,如果未能解决你的问题,请参考以下文章
SQL SERVER中,如何把一个表中的数据导入到另一个表中?