0

I am trying to select Max(ID) for all tables in my database. I tried the below query but there is no AUTO-INCREMENT column available. Is there something else that I can try?

SELECT TABLE_NAME, AUTO_INCREMENT
FROM   information_schema.TABLES
WHERE  TABLE_SCHEMA = 'mydb'
4

2 回答 2

4

您是否尝试获取数据库中每个 IDENTITY 列的最大值?这可以通过修改先前答案中的脚本来检查 sys.columns 表上的 is_identity 列来实现。

 CREATE TABLE #x(t NVARCHAR(520), c BIGINT);

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'';

SELECT @sql = @sql + N'INSERT #x SELECT ''' 
  + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ''',
  MAX(' + c.name + ') FROM '
  + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'

FROM sys.columns C
    INNER JOIN sys.tables T ON C.object_id = T.object_id
    INNER JOIN sys.schemas s ON S.schema_id = T.schema_id
WHERE is_identity = 1;

EXEC sp_executesql @sql;

SELECT t, c FROM #x;

DROP TABLE #x;
于 2013-09-09T22:06:37.630 回答
0
CREATE TABLE #x(t NVARCHAR(520), c BIGINT);

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'';

SELECT @sql = @sql + N'INSERT #x SELECT ''' 
  + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ''',
  MAX(ID) FROM '
  + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
INNER JOIN sys.columns AS c
ON t.[object_id] = c.[object_id]
WHERE c.name = N'ID';

EXEC sp_executesql @sql;

SELECT t, c FROM #x;

DROP TABLE #x;
于 2013-09-09T21:48:38.960 回答