How do I compare two columns for equality in SQL Server?

后端 未结 7 1028
忘掉有多难
忘掉有多难 2020-12-06 04:15

I have two columns that are joined together on certain criteria, but I would also like to check if two other columns are identical and then return a bit field if they are.

7条回答
  •  一生所求
    2020-12-06 04:22

    Regarding David Elizondo's answer, this can give false positives. It also does not give zeroes where the values don't match.

    Code

    DECLARE @t1 TABLE (
        ColID   int     IDENTITY,
        Col2    int
    )
    
    DECLARE @t2 TABLE (
        ColID   int     IDENTITY,
        Col2    int
    )
    
    INSERT INTO @t1 (Col2) VALUES (123)
    INSERT INTO @t1 (Col2) VALUES (234)
    INSERT INTO @t1 (Col2) VALUES (456)
    INSERT INTO @t1 (Col2) VALUES (1)
    
    INSERT INTO @t2 (Col2) VALUES (123)
    INSERT INTO @t2 (Col2) VALUES (345)
    INSERT INTO @t2 (Col2) VALUES (456)
    INSERT INTO @t2 (Col2) VALUES (2)
    
    SELECT
        t1.Col2 AS t1Col2,
        t2.Col2 AS t2Col2,
        ISNULL(NULLIF(t1.Col2, t2.Col2), 1) AS MyDesiredResult
    FROM @t1 AS t1
    JOIN @t2 AS t2 ON t1.ColID = t2.ColID
    

    Results

         t1Col2      t2Col2 MyDesiredResult
    ----------- ----------- ---------------
            123         123               1
            234         345             234 <- Not a zero
            456         456               1
              1           2               1 <- Not a match
    

提交回复
热议问题