如何使用子查询更新多行

时间:2012-10-24 17:49:34

标签: sql sql-server

当我执行子查询时一切正常如预期的那样现在我使用相同的查询来根据子查询结果更新列,但是它说子查询返回的行超过1行才有意义。怎么办?我解决了这个问题..

begin transaction
update trn_RatingAuto                                                        
set Rate  = 0 
where rate = (
SELECT ar.Rate
FROM trn_account ta
INNER JOIN trn_risk tr  ON ta.AccountId=tr.AccountId
inner join trn_option ot on tr.riskid = ot.riskid
INNER JOIN trn_Rating ra ON ot.RatingId = ra.RatingId
INNER JOIN trn_RatingAuto ar on ra.RatingId = ar.RatingId
where  ar.Rate is null 
)

4 个答案:

答案 0 :(得分:2)

您需要使用IN代替=

update trn_RatingAuto
set Rate  = 0 
where rate IN (
  SELECT ar.Rate
  FROM trn_account ta
  INNER JOIN trn_risk tr  ON ta.AccountId=tr.AccountId
  inner join trn_option ot on tr.riskid = ot.riskid
  INNER JOIN trn_Rating ra ON ot.RatingId = ra.RatingId
  INNER JOIN trn_RatingAuto ar on ra.RatingId = ar.RatingId
  where  ar.Rate is null 
)

编辑:

您也可以通过这种方式进行更新:

update ar
set Rate  = 0 
FROM trn_account ta
INNER JOIN trn_risk tr  ON ta.AccountId=tr.AccountId
inner join trn_option ot on tr.riskid = ot.riskid
INNER JOIN trn_Rating ra ON ot.RatingId = ra.RatingId
INNER JOIN trn_RatingAuto ar on ra.RatingId = ar.RatingId
where  ar.Rate is null

答案 1 :(得分:0)

将您的位置从=更改为in

begin transaction
update trn_RatingAuto                                                        
set Rate  = 0 
where rate in (
SELECT ar.Rate
FROM trn_account ta
INNER JOIN trn_risk tr  ON ta.AccountId=tr.AccountId
inner join trn_option ot on tr.riskid = ot.riskid
INNER JOIN trn_Rating ra ON ot.RatingId = ra.RatingId
INNER JOIN trn_RatingAuto ar on ra.RatingId = ar.RatingId
where  ar.Rate is null 
)

答案 2 :(得分:0)

如果您想要更新多行,则需要将查询更改为“更新自”查询...

sql server 2005 'update from' query

像:

 update trn_RatingAuto
   set Rate  = 0  
 from trn_RatingAuto
 join (...

答案 3 :(得分:0)

我在SQLServer2008R2上编写了这个脚本,也许它会帮助你

UPDATE x
SET x.Rate  = 0 
FROM (
      SELECT ar.Rate
      FROM trn_account ta INNER JOIN trn_risk tr  ON ta.AccountId=tr.AccountId
                          INNER JOIN trn_option ot ON tr.riskid = ot.riskid
                          INNER JOIN trn_Rating ra ON ot.RatingId = ra.RatingId
                          INNER JOIN trn_RatingAuto ar ON ra.RatingId = ar.RatingId
      WHERE  ar.Rate is null
      ) x