如何在SQL Server中使用join和case更新表?

时间:2019-04-24 10:02:10

标签: sql sql-server

更新表可能有问题

    UPDATE FGJ
SET  
     [base_title]=
                        case when NL.[atypcode_type] = 105 THEN NL.[ATYPCODE] 
                        ELSE 0
                    END ,
     [base_mande]= 
                        case when  NL.[atypcode_type] = 105 and NL.[ATYPCODE]=FGJ.[base_title] 
                        THEN NL.[mande]+FGJ.[base_mande]
                        ELSE 0.00
                    END 
                    ,....



from [dbo].[SuratMali_FinalGozareshJame] FGJ
INNER JOIN #tmp_notLinked NL 
       ON FGJ.CodeL = NL.[codelfinal]

此代码不适用于更新表 感谢您阅读我的问题

1 个答案:

答案 0 :(得分:0)

如果将更新分为两个更新,可以避免使用CASE

UPDATE FGJ
SET  
     [base_title]= NL.[ATYPCODE] -- however, this case had different condition in your original query!
     [base_mande]= NL.[mande]+FGJ.[base_mande]
FROM [SuratMali_FinalGozareshJame] FGJ
INNER JOIN #tmp_notLinked NL 
       ON FGJ.CodeL = NL.[codelfinal]
WHERE NL.[atypcode_type] = 105 and NL.[ATYPCODE] = FGJ.[base_title] 


UPDATE FGJ
SET  
     [base_title]= 0 -- however, this case had different condition!
     [base_mande]= 0
FROM [SuratMali_FinalGozareshJame] FGJ
INNER JOIN #tmp_notLinked NL 
       ON FGJ.CodeL = NL.[codelfinal]
WHERE NL.[atypcode_type] != 105 or NL.[ATYPCODE] != FGJ.[base_title] 

但是,正如我在代码中提到的那样,您的case条件是不同的。如果确实如此(不是错别字),则必须为每个条件创建update

如果使用子查询,也可以重写未明确声明inner join的解决方案(请参见下面的内容)。此解决方案假定子查询仅返回一个值(例如,如果NL。[codelfinal]是主键)。但是,无论如何,联接都隐藏在语法中,没有必要像这样重写它。

UPDATE FGJ
SET  
     [base_mande]= (
        SELECT NL.[mande]
        FROM #tmp_notLinked NL
        WHERE FGJ.CodeL = NL.[codelfinal] and 
              NL.[atypcode_type] = 105 and 
              NL.[ATYPCODE] = FGJ.[base_title] 
      ) + FGJ.[base_mande]
FROM [SuratMali_FinalGozareshJame] FGJ