SQL Server compare results of two queries that should be identical

前端 未结 6 2014
面向向阳花
面向向阳花 2020-12-24 11:14

I am modifying a sql server 2005 stored procedure slightly for performance, and I would like to quickly make sure the old stored proc and the new one return the exact same r

6条回答
  •  情话喂你
    2020-12-24 11:46

    To complete @jabs answer, you can use the following template to get the difference between two queries:

    WITH q1 AS ()
       , q2 AS ()
    SELECT * FROM q1 EXCEPT SELECT * FROM q2
    UNION ALL (
    SELECT * FROM q2 EXCEPT SELECT * FROM q1);
    

    Example 1: This returns 0 rows, as the queries are identical

    WITH q1 AS (SELECT * FROM my_table)
       , q2 AS (SELECT * FROM my_table)
    SELECT * FROM q1 EXCEPT SELECT * FROM q2
    UNION ALL (
    SELECT * FROM q2 EXCEPT SELECT * FROM q1);
    

    Example 2: This returns the different rows between the queries (where foo = 'bar')

    WITH q1 AS (SELECT * FROM my_table)
       , q2 AS (SELECT * FROM my_table WHERE foo <> 'bar')
    SELECT * FROM q1 EXCEPT SELECT * FROM q2
    UNION ALL (
    SELECT * FROM q2 EXCEPT SELECT * FROM q1);
    

    Example 3: Just for fun, you can check that the query in Example 2 is identical to queries the rows where foo = 'bar'.

    WITH q1 AS (
    
        WITH q1 AS (SELECT * FROM my_table)
           , q2 AS (SELECT * FROM my_table WHERE foo <> 'bar')
        SELECT * FROM q1 EXCEPT SELECT * FROM q2
        UNION ALL (
        SELECT * FROM q2 EXCEPT SELECT * FROM q1)
    
    )
       , q2 AS (SELECT * FROM my_table WHERE foo = 'bar')
    SELECT * FROM q1 EXCEPT SELECT * FROM q2
    UNION ALL (
    SELECT * FROM q2 EXCEPT SELECT * FROM q1);
    

提交回复
热议问题