1
我想從所有數據庫中的所有表中獲取數據庫名稱,模式名稱,表名和最大id值。使用下面的查詢,我得到DBname,Schema和TableName,但無法弄清楚如何將max(id)值也放入表中。SQL從所有數據庫的所有表中獲取最大id值
DECLARE @DBName VARCHAR(256)
DECLARE @varSQL VARCHAR(256)
DECLARE @getDBName CURSOR
SET @getDBName = CURSOR FOR SELECT name FROM sys.databases
CREATE TABLE #TmpTable (
DBName VARCHAR(256),
SchemaName VARCHAR(256),
TableName VARCHAR(256)
)
OPEN @getDBName
FETCH NEXT FROM @getDBName INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @varSQL = 'USE ' + @DBName + ';
INSERT INTO #TmpTable
SELECT '''+ @DBName + ''' AS DBName,
SCHEMA_NAME(schema_id) AS SchemaName,
name AS TableName
FROM sys.tables'
EXEC(@varSQL)
FETCH NEXT FROM @getDBName INTO @DBName
END
CLOSE @getDBName
DEALLOCATE @getDBName
SELECT * FROM #TmpTable
DROP TABLE #TmpTable
你假設所有表具有相同的鍵字段的名字嗎? – asmgx
是的,id是字段名稱 –