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

后端 未结 2 1060
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 21:36

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 co

相关标签:
2条回答
  • 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
    
    0 讨论(0)
  • 2021-01-28 22:22

    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
    
    0 讨论(0)
提交回复
热议问题