SQL Loop through all tables and get the max value from a specific column

浪子不回头ぞ 提交于 2019-12-25 07:59:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!