这是你想要的吗?
ID Column OldValue New Value
1 City Phoenix Denver
2 Department Order Process Marketing
2 City San Diego San jose
这是动态代码:
DECLARE @sqlStm varchar(max);
DECLARE @sqlSelect varchar(max);
DECLARE @tablename varchar(200);
SET @tablename = 'testtable';
-- Assume table has ID column and State column.
SET @sqlSelect = ''
SET @sqlStm = 'WITH old AS
(
SELECT *
FROM '+@tablename+'
WHERE State=''O''
), new AS
(
SELECT *
FROM '+@tablename+'
WHERE State=''N''
)';
DECLARE @aCol varchar(128)
DECLARE curCols CURSOR FOR
SELECT column_name
FROM information_schema.columns
WHERE table_name = @tablename
AND UPPER(column_name) NOT IN ('ID','STATE')
OPEN curCols
FETCH curCols INTO @aCol
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @sqlStm = @sqlStm +
', changed'+@aCol+' AS
(
SELECT n.ID, '''+@aCol+''' AS [Column], o.['+@aCol+'] AS oldValue, n.['+@aCol+'] AS newValue
FROM new n
JOIN old o ON n.ID = o.ID AND n.['+@aCol+'] != o.['+@aCol+']
)'
IF LEN(@sqlSelect) > 0 SET @sqlSelect = @sqlSelect + ' UNION ALL '
SET @sqlSelect = @sqlSelect + '
SELECT * FROM changed'+@aCol
FETCH curCols INTO @aCol
END
CLOSE curCols
DEALLOCATE curCols
SET @sqlSelect = @sqlSelect + '
ORDER BY id, [Column]'
PRINT @sqlStm+@sqlSelect
EXEC (@sqlStm+@sqlSelect)
在我的测试中输出以下内容:
WITH old AS
(
SELECT *
FROM testtable
WHERE State='O'
), new AS
(
SELECT *
FROM testtable
WHERE State='N'
), changedName AS
(
SELECT n.ID, 'Name' AS [Column], o.[Name] AS oldValue, n.[Name] AS newValue
FROM new n
JOIN old o ON n.ID = o.ID AND n.[Name] != o.[Name]
), changedDepartment AS
(
SELECT n.ID, 'Department' AS [Column], o.[Department] AS oldValue, n.[Department] AS newValue
FROM new n
JOIN old o ON n.ID = o.ID AND n.[Department] != o.[Department]
), changedCity AS
(
SELECT n.ID, 'City' AS [Column], o.[City] AS oldValue, n.[City] AS newValue
FROM new n
JOIN old o ON n.ID = o.ID AND n.[City] != o.[City]
)
SELECT * FROM changedName UNION ALL
SELECT * FROM changedDepartment UNION ALL
SELECT * FROM changedCity
ORDER BY id, [Column]
原答案如下:
我会这样做——因为我认为它比其他可能更快的方式更清晰:
with old as
(
Select ID, Name,Department,City
From table1
Where State='O'
), new as
(
Select ID, Name,Department,City
From table1
Where State='N'
), oldDepartment as
(
Select ID, 'Department' as Column, o.Department as oldValue, n.Department as newValue
From new
join old on new.ID = old.ID and new.Department != old.Department
), oldCity as
(
Select ID, 'City' as Column, o.City as oldValue, n.City as newValue
From new
join old on new.ID = old.ID and new.City != old.City
)
select * from oldDepartment
union all
select * from oldCity
根据许多事情(表和索引的大小等),它实际上可能比使用数据透视或案例或分组更快。这真的取决于你的数据。如果这是一次性的,我会选择最容易理解的。