2015-12-10 34 views

回答

1

有沒有簡單方式來做到這一點。一種方法是這樣的:

select max(lastUpdateDate) 
from (select lastUpdateDate from t1 union all 
     select lastUpdateDate from t2 union all 
     . . . 
     select lastUpdateDate from t470 
    ) t; 

您可以構建該查詢。一個簡單的方法是做這樣的事情:

select replace('  select lastUpdateDate from @table union all', 
       @table, @table_name) 
from information_schema.columns 
where column_name = 'lastUpdateDate'; 

(你可能要採取的模式考慮在內。)然後複製結果,並將其格式化成一個查詢。

另一個有用的功能是sp_MSforeachtable。它是無證的,但有很多這方面的文章,例如這個one。如果某些表缺少列,這可能有點麻煩。

+0

好吧,我明白了,但什麼你的意思是最後的t; ,這是我應該放在那裏的表名嗎? –

+0

它是一個表別名,SQL Server需要''from'子句中的子查詢。 –

0

正如已經說過的那樣,沒有任何方法;另一個可能是這個,但請記住它使用動態SQL的所有優點和缺點。

而且我建議設置列名,你喜歡的,而不是所有的dateime者中尋找它像我一樣,如果它總是相同

DECLARE @ParmDefinition nvarchar(500); 
DECLARE @tableName nvarchar(max) 
DECLARE @columnName nvarchar(max) 
DECLARE @sqlQuery nvarchar(max) 
DECLARE @strDate nvarchar(max) 
DECLARE @maxDate DateTime 
DECLARE @resDate DateTime 
DECLARE @resTable nvarchar(max) 
SELECT @resDate = '1900-01-01', @resTable = '' 
DECLARE curTables CURSOR FOR 
SELECT t.name, c.Name 
FROM sys.tables t INNER JOIN sys.columns c ON c.object_id = t.object_id 
WHERE t.[type] = 'U' AND c.system_type_id = '61' 
OPEN curTables 
FETCH NEXT FROM curTables INTO @tableName, @columnName 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    SET @ParmDefinition = N'@maxOUT DateTime OUTPUT'; 
    SET @sqlQuery = N'SELECT @maxOUT = MAX (' + @columnName + ') FROM ' + @tableName; 
    exec sp_executesql @sqlQuery,@ParmDefinition, @maxOUT = @strDate OUTPUT; 
    SET @maxDate = CONVERT(DATETIME, @strDate, 102) 
    IF (@maxDate > @resDate) 
     SELECT @resDate = @maxDate, @resTable = @tableName 
    FETCH NEXT FROM curTables INTO @tableName, @columnName 
END 
CLOSE curTables 
DEALLOCATE curTables 
SELECT @tableName TableName, @resDate LastUpdateDate 
相關問題