SQL从所有数据库中的所有表中获取最大id值

时间:2017-07-31 05:37:45

标签: sql tsql

我想从所有数据库中的所有表中获取数据库名称,模式名称,表名称和最大ID值。使用以下查询,我得到DBname,Schema和TableName,但无法弄清楚如何将max(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

1 个答案:

答案 0 :(得分:1)

SELECT
     '@DBName' AS DBName, 
      IDENT_CURRENT(Name) MaxId,
      SCHEMA_NAME(Schema_ID) AS SchemaName,
      name AS TableName
FROM sys.Tables