过程Regist_Update子查询返回了多个值

时间:2019-07-17 04:14:09

标签: sql-server sql-update

  

消息512,级别16,状态1,过程Regist_Update,第6行[批处理开始第0行]   子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。   该声明已终止。

use DBRegist
UPDATE Regist
SET Regist.Major = upload.Major
FROM Regist
    INNER JOIN upload
    ON Regist.Reg_ID = upload.ID
WHERE Regist.Period='2018' or Regist.Period='2017' or Regist.Period='2016'

2 个答案:

答案 0 :(得分:0)

由于您的上载表针对每个ID返回多于一行。您可以确保每个ID仅获得一行,这样就不会影响更新。我只是按专业订购的,您可以根据需要订购其中任何一个。另外,您可以在两者之间进行舍弃,而不是给予或从句,我也更改了您的where条件。

use DBRegist
UPDATE Regist
SET Regist.Major = upload.Major
FROM Regist
    INNER JOIN (select ID, major, row_number() over (partition by ID order by major) rownum from  upload) upload

    ON Regist.Reg_ID = upload.ID and upload.rownum = 1 
WHERE Regist.Period between '2016' and '2018' 

答案 1 :(得分:0)

如果您改用可更新的CTE,则可能根本不需要更改逻辑:

WITH cte AS (
    SELECT r.Major, u.Major AS MajorSource
    FROM Regist r
    INNER JOIN upload u
        ON r.Reg_ID = u.ID
    WHERE r.Period = IN ('2016', '2017', '2018')
)

UPDATE cte
SET Major = MajorSource;