问题
I'm trying to create an audit table that checks the loaded date for that table.
Basically, I want to loop through all tables in the database and check for a specific column - LoadedDate
and return the max value for that column for each table
SELECT TABLE_NAME
INTO #TableList
FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name = 'LoadedDate'
SELECT MAX(LoadedDate) FROM @TableName -- I guess using a cursor to loop through #TableList
in to a results table
TableName LoadedDate
Table 1 2016-06-01
Table 2 2016-07-01
Table 3 2016-06-01
and so on.
回答1:
You can try this code, but it will consume some time
SELECT TABLE_NAME,TABLE_SCHEMA
INTO #TableList
FROM INFORMATION_SCHEMA.COLUMNS
WHERE column_name = 'LoadedDate'
CREATE TABLE #TempResult (TableName VARCHAR(100), MaxDate DATETIME2)
DECLARE @TableName VARCHAR(100)
,@TableSchema VARCHAR(100)
DECLARE @SqlQuery NVARCHAR(MAX)
WHILE(EXISTS(SELECT TOP(1) * FROM #TableList))
BEGIN
SELECT TOP(1) @TableName = TABLE_NAME, @TableSchema = TABLE_SCHEMA FROM #TableList
DELETE #TableList WHERE TABLE_NAME = @TableName
SET @TableName = @TableSchema +'.'+ @TableName
SET @SqlQuery = 'SELECT '''+@TableName+''' AS ''TableName'', MAX(UpdatedDate) AS MaxDate FROM '+ @TableName
INSERT INTO #TempResult
EXECUTE sp_executesql @SqlQuery
END
SELECT * from #TempResult
DROP TABLE #TableList
DROP TABLE #TempResult
回答2:
Perhaps a little dynamic SQL
Select Table_Name = cast('' as varchar(150))
,LoadedDate = GetDate()
Into #TableList
Where 1=0
Declare @SQL varchar(max) = '>>>'
Select @SQL = @SQL + SQL
From (
Select Table_Name,SQL='Union All Select Table_Name='''+Table_Name+''',LoadedDate=max(LoadedDate) From ['+Table_Name+'] '
From INFORMATION_SCHEMA.COLUMNS
Where column_name Like '%UTC%' --= 'LoadedDate'
) A
Set @SQL = Replace(@SQL,'>>>Union All','Insert Into #TableList ')
Exec(@SQL)
Select * from #TempResult
来源:https://stackoverflow.com/questions/38559293/sql-loop-through-all-tables-and-get-the-max-value-from-a-specific-column