如何在更新同一列的SQL Server语句时使用多种情况

时间:2018-10-23 18:13:02

标签: sql-server

我想编写一个包含多个CASE WHEN语句的查询,以更新同一列(称为“ Assert_True”)。基本上,我希望查询断言所有列的a.col_1中的值在b.col_1中都相同。预期的结果是一个临时表,然后我可以对Assert_True列进行过滤,以查找哪对列不具有相同的值。到目前为止,我已经编写了以下代码:

SELECT 
    CASE WHEN a.col_1 = b.col_1 THEN 0 ELSE 1 END AS Assert_True, 
    a.col_1, b.col_1,
    CASE WHEN a.col_2 = b.col_2 THEN 0 ELSE 1 END AS Assert_True, 
    a.col_2, b.col_2,
    CASE WHEN a.col_3 = b.col_3 THEN 0 ELSE 1 END AS Assert_True, 
    a.col_3, b.col_3
INSERT INTO #TempTable
FROM
    database.schema.table1 a
JOIN 
    database.schema.table2 b ON a.ID = b.ID

1 个答案:

答案 0 :(得分:1)

只有一个case语句可以对多个测试使用OR:

SELECT 
    CASE WHEN a.col_1 <> b.col_1 OR a.col_2 <> b.col_2 OR a.col_3 <> b.col_3 THEN 0 ELSE 1 END AS Assert_True, 
    a.col_1, b.col_1,    
    a.col_2, b.col_2,   
    a.col_3, b.col_3
INSERT INTO #TempTable
FROM
    database.schema.table1 a
JOIN 
    database.schema.table2 b ON a.ID = b.ID

或者,根据您的需要:

SELECT 
    CASE WHEN a.col_1 <> b.col_1 THEN 'col_1'
         WHEN a.col_2 <> b.col_2 THEN 'col_2'
         WHEN a.col_3 <> b.col_3 THEN 'col_3' 
         ELSE 'all matched' 
         END AS Assert_True, 
    a.col_1, b.col_1,    
    a.col_2, b.col_2,   
    a.col_3, b.col_3
INSERT INTO #TempTable
FROM
    database.schema.table1 a
JOIN 
    database.schema.table2 b ON a.ID = b.ID