比较SQL Server

时间:2017-11-11 02:48:15

标签: sql sql-server

我在SQL Server中有一个包含id, name1, desc1, name2, desc2列的表。我想比较name1, name2值和desc1, desc2值,并在另一列中显示结果'备注'

像这样的东西

id | name1 | desc1 | name2 | desc2

输出应该像

id | name1 | Desc1 | name2 | desc2 | Remarks
---+-------+-------+-------+-------+--------------------------
 1 | abc   | test1 | xyz   | test2 | Desc and name different
 2 | def   | test3 | ghi   | test3 | Name different

表格中有多列如此比较。

有人可以帮帮我吗?提前谢谢。

5 个答案:

答案 0 :(得分:0)

你可以尝试一下。

SELECT 
    name1
    ,Desc1
    ,name2
    ,Desc2
    ,(CASE WHEN name1<>name2 THEN 'Name different'
          WHEN Desc1<>Desc2 THEN 'Desc different'
          WHEN name1<>name2 AND Desc1<>Desc2 THEN 'Name and Desc different' 
     END)
FROM tbl

答案 1 :(得分:0)

最好的选择是创建一个用户定义的函数,该函数可以评估您需要检查的字段之间的差异,并且可以返回正确的&#34;备注&#34;串。我已将SQLFiddle设置为演示:http://sqlfiddle.com/#!6/aa2cc65/2

答案 2 :(得分:0)

SELECT name1 ,Desc1 ,name2 ,Desc2 ,
(CASE 
WHEN (name1<>name2) and (Desc1<>Desc2) THEN 'Name and Desc different' 
WHEN name1<>name2 THEN 'Name different' 
WHEN Desc1<>Desc2 THEN 'Desc different'
WHEN (name1=name2) and (Desc1=Desc2) THEN 'Name and Desc Same' 
END) as Remarks
FROM tbl

答案 3 :(得分:0)

SELECT id, name1, desc1, name2, desc2, 
        (CASE  WHEN (ISNULL(name1, '') <> ISNULL(name2, '')) AND  (ISNULL(desc1, '') <> ISNULL(desc2, '')) THEN 'Desc and name different' 
                  WHEN (ISNULL(name1, '') = ISNULL(name2, '')) AND (ISNULL(desc1, '') <> ISNULL(desc2, '')) THEN 'Desc different' 
                  WHEN (ISNULL(name1, '') <> ISNULL(name2, '')) AND (ISNULL(desc1, '') = ISNULL(desc2, '')) THEN 'Name different' 
                  WHEN (ISNULL(name1, '') = ISNULL(name2, '')) AND (ISNULL(desc1, '') = ISNULL(desc2, '')) THEN 'Not different' 
        END) as Remarks
FROM tbl

答案 4 :(得分:0)

select id, name1, Desc1, name2, desc2,   
   CASE WHEN trim(ISNULL(name1, 'NULL')) <> trim(ISNULL(name2, 'NULL')) AND
             trim(ISNULL(desc1, 'NULL')) <> trim(ISNULL(desc2, 'NULL'))
        THEN 'name and desc different'

        WHEN trim(ISNULL(name1, 'NULL')) <> trim(ISNULL(name2, 'NULL'))
        THEN 'name different' 

        WHEN trim(ISNULL(desc1, 'NULL')) <> trim(ISNULL(desc2, 'NULL')) 
        THEN 'desc different' END as Remarks
from yourtable

如果值为null,除非您专门检查,否则不会进行比较。 您可能不需要修剪空格。 我没有机会通过sql server运行它。