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

后端 未结 2 1061
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  时光取名叫无心
    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
    

提交回复
热议问题