我的数据库的每个表中的每一行都有一个 RowUpdateDateTime 列,这是更新或插入特定行的最新时间。每个表中还有 1 到 7 个不同的数据源;有的有1个,有的有7个。
基本上,我试图遍历这些表,并在适用的情况下为这些表中的每一个找到这些源中的每一个的最新 RowUpdateDateTime。这是我和一位同事为此写的很长的查询。它是功能性的,但我怀疑可以重写。
IF OBJECT_ID('tempdb..#SourceID') IS NOT NULL
BEGIN
DROP TABLE #SourceID
END
IF OBJECT_ID('tempdb..#Tables') IS NOT NULL
BEGIN
DROP TABLE #Tables
END
IF OBJECT_ID('tempdb..#UpdateCount') IS NOT NULL
BEGIN
DROP TABLE #UpdateCount
END
GO
CREATE TABLE #SourceID
(
SourceID varchar(4),
CounterID int
)
INSERT INTO #SourceID (SourceID,CounterID)
SELECT 'ZEND',1
UNION ALL
SELECT 'ABC',2
UNION ALL
SELECT 'DEF',3
UNION ALL
SELECT 'GHI',4
UNION ALL
SELECT 'JKL',5
UNION ALL
SELECT 'MNO',6
UNION ALL
SELECT 'PQR',7
UNION ALL
SELECT 'STU',8
GO
CREATE TABLE #Tables
(
Name varchar(100),
CounterID int
)
INSERT INTO #Tables (Name,CounterID)
SELECT 'livendb..Table1',1
UNION ALL
SELECT 'livendb..Table2',2
UNION ALL
SELECT 'livendb..Table3',3
UNION ALL
SELECT 'livendb..Table4',4
UNION ALL
SELECT 'livendb..Table5',5
UNION ALL
SELECT 'livendb..Table6',6
UNION ALL
SELECT 'livendb..Table7',7
UNION ALL
SELECT 'livefdb..Table8',8
UNION ALL
SELECT 'livefdb..Table9',9
UNION ALL
SELECT 'livefdb..Table10',10
UNION ALL
SELECT 'livefdb..Table11',11
UNION ALL
SELECT 'livefdb..Table12',12
UNION ALL
SELECT 'livefdb..Table13',13
GO
Declare @counter varchar(10)
Declare @tablename varchar(100)
Declare @query varchar(1100)
Declare @sourceid varchar(4)
Declare @sourcecounter varchar(10)
CREATE TABLE #UpdateCount
(
SourceID varchar(3),
TableName Varchar(100),
MaxRowUpdateDateTime datetime,
--TotalRowCount int
)
SET @sourcecounter = (SELECT COUNT(*) FROM #SourceID)
SET @counter = (SELECT COUNT (*) FROM #Tables)
WHILE @sourcecounter >= 0
BEGIN
SET @sourceid = (SELECT SourceID FROM #SourceID WHERE CounterID = (@sourcecounter))
IF @sourceid <> 'ZEND'
BEGIN
WHILE @counter >=0
BEGIN
SET @tablename = (SELECT Name FROM #Tables WHERE CounterID = (@counter))
IF @counter <> 0
BEGIN
SET @query = 'INSERT INTO #UpdateCount (SourceID,TableName,MaxRowUpdateDateTime)
VALUES (
(SELECT SourceID FROM #SourceID WHERE CounterID = '+@sourcecounter+')
,(SELECT Name FROM #Tables WHERE CounterID = '+@counter+')
,(SELECT MAX(RowUpdateDateTime) FROM '+@tablename+' WHERE SourceID =
(SELECT SourceID FROM #SourceID WHERE CounterID = '+@sourcecounter+')))'
EXECUTE (@query)
END
SET @counter = (@counter-1)
END
END
SET @sourcecounter = (@sourcecounter-1)
SET @counter = (SELECT COUNT (*) FROM #Tables)
END
SELECT SourceID
,SUBSTRING(TableName,10,22) as TableName
,MaxRowUpdateDateTime
--,TotalRowCount
FROM #UpdateCount
Where MaxRowUpdateDateTime IS NOT NULL
ORDER BY TableName
DROP TABLE #Tables
DROP TABLE #UpdateCount
DROP TABLE #SourceID