下面是一些使用 2 种方法的示例 SQL。
-
FOR
XML
&
HASHBYTES
- EXCEPT
IF OBJECT_ID('tempdb..#tmpTest') IS NOT NULL DROP TABLE #tmpTest;
CREATE TABLE #tmpTest (
id int identity(1,1) primary key,
col1 decimal(10,2),
col2 varchar(30)
);
insert into #tmpTest (col1, col2) values
(1,'val1'),
(null,'val2'),
(3,null),
(4,'val4')
-- ,(5,'monkeywrench')
;
declare @SQL1 VARCHAR(1000);
declare @SQL2 VARCHAR(1000);
declare @SQLHASH VARCHAR(3000);
declare @SQLEXCEPT VARCHAR(5000);
set @SQL1 = 'select col1, col2
from #tmpTest
where (col1 is null or col1 between 1 and 4)
';
set @SQL2 = 'select col1, col2
from #tmpTest
where (col2 is null or col2 is not null)
';
set @SQLHASH = 'select
IIF(LEN(query1.x) = LEN(query2.x) AND HASHBYTES(''SHA2_512'', query1.x) = HASHBYTES(''SHA2_512'', query2.x),''true'',''false'') as SameHash
from (
'+ @SQL1 +'
order by 1, 2
for xml auto
) query1(x)
cross join (
'+ @SQL2 +'
order by 1, 2
for xml auto
) query2(x)';
--select @SQLHASH as SQLHASH;
execute(@SQLHASH);
set @SQLEXCEPT = 'select
IIF(count(*) = 0,''true'',''false'') as SameRecords
from (
select * from
(
'+ @SQL1 +'
except
'+ @SQL2 +'
) as q1exceptq2
union all
select * from (
'+ @SQL2 +'
except
'+ @SQL1 +'
) as q2exceptq1
) q';
--select @SQLEXCEPT as SQLEXCEPT;
execute(@SQLEXCEPT);
在此示例中,两个动态查询都返回“true”。
但请注意,仅仅因为结果集相同,并不意味着使用的标准是等效的。
他们目前返回相同的结果可能只是运气不好。
(只需取消注释 monkeywrench 记录以从两者中获取错误)
另外,关于 FOR XML。当其中一个 ORDER BY 不同时,那么生成的 XML 和 HASH 也会不同。
虽然使用 EXCEPT,但您只能在末尾添加 ORDER BY,因为它会对组合的结果集进行排序。