-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathtSQLt.Private_CompareTables.ssp.sql
64 lines (60 loc) · 2.27 KB
/
tSQLt.Private_CompareTables.ssp.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
IF OBJECT_ID('tSQLt.Private_CompareTables') IS NOT NULL DROP PROCEDURE tSQLt.Private_CompareTables;
GO
---Build+
GO
CREATE PROCEDURE tSQLt.Private_CompareTables
@Expected NVARCHAR(MAX),
@Actual NVARCHAR(MAX),
@ResultTable NVARCHAR(MAX),
@ColumnList NVARCHAR(MAX),
@MatchIndicatorColumnName NVARCHAR(MAX)
AS
BEGIN
DECLARE @cmd NVARCHAR(MAX);
DECLARE @RestoredRowIndexCounterColName NVARCHAR(MAX);
SET @RestoredRowIndexCounterColName = @MatchIndicatorColumnName + '_RR';
SELECT @cmd =
'
INSERT INTO ' + @ResultTable + ' (' + @MatchIndicatorColumnName + ', ' + @ColumnList + ')
SELECT
CASE
WHEN RestoredRowIndex.'+@RestoredRowIndexCounterColName+' <= CASE WHEN [_{Left}_]<[_{Right}_] THEN [_{Left}_] ELSE [_{Right}_] END
THEN ''=''
WHEN RestoredRowIndex.'+@RestoredRowIndexCounterColName+' <= [_{Left}_]
THEN ''<''
ELSE ''>''
END AS ' + @MatchIndicatorColumnName + ', ' + @ColumnList + '
FROM(
SELECT SUM([_{Left}_]) AS [_{Left}_],
SUM([_{Right}_]) AS [_{Right}_],
' + @ColumnList + '
FROM (
SELECT 1 AS [_{Left}_], 0[_{Right}_], ' + @ColumnList + '
FROM ' + @Expected + '
UNION ALL
SELECT 0[_{Left}_], 1 AS [_{Right}_], ' + @ColumnList + '
FROM ' + @Actual + '
) AS X
GROUP BY ' + @ColumnList + '
) AS CollapsedRows
CROSS APPLY (
SELECT TOP(CASE WHEN [_{Left}_]>[_{Right}_] THEN [_{Left}_]
ELSE [_{Right}_] END)
ROW_NUMBER() OVER(ORDER BY(SELECT 1))
FROM (SELECT 1
FROM ' + @Actual + ' UNION ALL SELECT 1 FROM ' + @Expected + ') X(X)
) AS RestoredRowIndex(' + @RestoredRowIndexCounterColName + ');';
EXEC (@cmd); --MainGroupQuery
SET @cmd = 'SET @r =
CASE WHEN EXISTS(
SELECT 1
FROM ' + @ResultTable +
' WHERE ' + @MatchIndicatorColumnName + ' IN (''<'', ''>''))
THEN 1 ELSE 0
END';
DECLARE @UnequalRowsExist INT;
EXEC sp_executesql @cmd, N'@r INT OUTPUT',@UnequalRowsExist OUTPUT;
RETURN @UnequalRowsExist;
END;
---Build-
GO