Can I use CASE statement in a JOIN condition?

前端 未结 9 1749
庸人自扰
庸人自扰 2020-11-22 09:32

The following image is a part of Microsoft SQL Server 2008 R2 System Views. From the image we can see that the relationship between sys.partitions and sys

9条回答
  •  抹茶落季
    2020-11-22 09:39

    Here I have compared the difference in two different result sets:

    SELECT main.ColumnName, compare.Value PreviousValue,  main.Value CurrentValue
    FROM 
    (
        SELECT 'Name' AS ColumnName, 'John' as Value UNION ALL
        SELECT 'UserName' AS ColumnName, 'jh001' as Value UNION ALL
        SELECT 'Department' AS ColumnName, 'HR' as Value UNION ALL
        SELECT 'Phone' AS ColumnName, NULL as Value UNION ALL
        SELECT 'DOB' AS ColumnName, '1993-01-01' as Value UNION ALL
        SELECT 'CreateDate' AS ColumnName, '2017-01-01' as Value UNION ALL
        SELECT 'IsActive' AS ColumnName, '1' as Value
    ) main
    INNER JOIN
    (
        SELECT 'Name' AS ColumnName, 'Rahul' as Value UNION ALL
        SELECT 'UserName' AS ColumnName, 'rh001' as Value UNION ALL
        SELECT 'Department' AS ColumnName, 'HR' as Value UNION ALL
        SELECT 'Phone' AS ColumnName, '01722112233' as Value UNION ALL
        SELECT 'DOB' AS ColumnName, '1993-01-01' as Value UNION ALL
        SELECT 'CreateDate' AS ColumnName, '2017-01-01' as Value UNION ALL
        SELECT 'IsActive' AS ColumnName, '1' as Value
    ) compare
    ON main.ColumnName = compare.ColumnName AND
    CASE 
        WHEN main.Value IS NULL AND compare.Value IS NULL THEN 0
        WHEN main.Value IS NULL AND compare.Value IS NOT NULL THEN 1
        WHEN main.Value IS NOT NULL AND compare.Value IS NULL THEN 1
        WHEN main.Value <> compare.Value THEN 1
    END = 1 
    

提交回复
热议问题