使用两个表在SQL Server中更新语句

时间:2017-08-24 08:55:26

标签: sql-server

这是我的查询

UPDATE #Student_tbl
SET MStudentId = (SELECT StudentId
                  FROM #StudentHistory_tbl
                  WHERE UserId NOT IN (SELECT UserId
                                       FROM #Student_tbl)
                 )

它会返回错误:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

3 个答案:

答案 0 :(得分:1)

当你写下来时,错误是相当明确的:

UPDATE #Student_tbl 
SET MStudentId = (
Select StudentId 
from #StudentHistory_tbl 
where UserId not in (select UserId from #Student_tbl)
)

您正在更新#Student_tbl中的所有行。您正在尝试将MSStudentId设置为等于多行,因为您的选择不会只返回一行。

您必须查看子查询,使其返回1行,或者将子查询加入'StudnetHistory_tbl,以便使用单个行值更新列。

答案 1 :(得分:1)

您可以在更新语句中使用JOINS。尝试这样的事情:

UPDATE  t1
SET     t1.MStudentId = t2.Studentid
FROM    #Student_tbl AS t1
        INNER JOIN #StudentHistory_tbl AS t2 ON t2.UserId = t1.UserId
WHERE   t1.MStudentId <> t2.Studentid;

答案 2 :(得分:0)

我认为你需要这样的东西

UPDATE #Student_tbl 
SET MStudentId= a.StudentId
from (Select StudentId,UserId from #StudentHistory_tbl ,#Student_tbl
where #StudentHistory_tbl.UserId <> #Student_tbl.UserId ) a
where a.UserId <> #Student_tbl.UserId

OR

UPDATE #Student_tbl 
SET MStudentId= a.StudentId
from (Select StudentId,UserId from #StudentHistory_tbl
where UserId not in (select UserId from #Student_tbl) ) a
where a.UserId not in (select UserId from #Student_tbl)