這是你想要的嗎?
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 '[email protected]+'
WHERE State=''O''
), new AS
(
SELECT *
FROM '[email protected]+'
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'[email protected]+' AS
(
SELECT n.ID, '''[email protected]+''' AS [Column], o.['[email protected]+'] AS oldValue, n.['[email protected]+'] AS newValue
FROM new n
JOIN old o ON n.ID = o.ID AND n.['[email protected]+'] != o.['[email protected]+']
)'
IF LEN(@sqlSelect) > 0 SET @sqlSelect = @sqlSelect + ' UNION ALL '
SET @sqlSelect = @sqlSelect + '
SELECT * FROM changed'[email protected]
FETCH curCols INTO @aCol
END
CLOSE curCols
DEALLOCATE curCols
SET @sqlSelect = @sqlSelect + '
ORDER BY id, [Column]'
PRINT @[email protected]
EXEC (@[email protected])
這在我的測試輸出如下:
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
取決於許多因素(表和索引等的大小),它實際上可能比使用樞軸或情況或分組更快。這真的取決於你的數據。如果這是一次性運行,我只是爲了最簡單的方式去尋找。
它是SqlServer嗎? –
您正在使用哪些DBMS? Postgres的?甲骨文? –
第一行不應該在列下面說城市嗎? – Hogan