带有子查询的SQL Update列,提供重复的结果

时间:2016-06-30 19:06:02

标签: sql-server asp.net-mvc

我是这个论坛和SQL语言的新手。尝试使用2个表从一个表更新列时遇到问题:

我有表订单,如下:

CREATE TABLE [dbo].[Orders]
 (
[IdOrder] INT NOT NULL PRIMARY KEY IDENTITY,
[IdLine] INT NOT NULL,
[OrderNo] NVARCHAR(50) NULL, 
[Description] NVARCHAR(50) NULL, 
[StartDate] DATETIME NULL, 
[EndDate] DATETIME NULL,
[Setpoint] INT NULL,
[Score] FLOAT NULL, 
[Status] NCHAR(10) NULL, 
CONSTRAINT [FK_Order_Line_IdArea] FOREIGN KEY ([IdLine]) REFERENCES [Line]  ([IdLine]) ON DELETE CASCADE ON UPDATE CASCADE
)

然后我有另一张桌子。这2个是一对多的关系

CREATE TABLE [dbo].[Productivity]
(
[IdProductivity] INT NOT NULL PRIMARY KEY, 
[IdOrder] INT NULL,
[Cont] INT NULL, 
CONSTRAINT [FK_Product_Order_IdOrder] FOREIGN KEY ([IdOrder]) REFERENCES      [Orders]([IdOrder]) ON DELETE CASCADE ON UPDATE CASCADE
)

我有关于这些表的som数据,当我执行此查询时,结果很好:

查询:

SELECT (CAST(Cont AS FLOAT) / CAST(Setpoint AS FLOAT)*100 ) AS col from Productivity LEFT OUTER JOIN Orders ON Productivity.IdOrder = Orders.IdOrder

结果: Query returning 4 rows with correct results

然后当我将子查询应用于更新Order表时,在Score列中使用以下查询:

UPDATE Orders
SET Score = col 
FROM (SELECT (CAST(Cont AS FLOAT) / CAST(Setpoint AS FLOAT)*100 ) AS col from Productivity LEFT OUTER JOIN Orders ON Productivity.IdOrder = Orders.IdOrder) 
AS query

我得到了这个结果:Query inserting only first and last result and duplicating them

如果我需要提供更多相关信息,请告诉我,非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我不会将此作为子查询进行正常更新

UPDATE Orders
SET Score = (CAST(Cont AS FLOAT) / CAST(Setpoint AS FLOAT)*100 ) 
FROM Productivity LEFT OUTER JOIN Orders 
ON Productivity.IdOrder = Orders.IdOrder