重新选择所选表的标识值

moh*_*111 2 t-sql sql-server

如何基于他们的最后一次计数重新选择.我已经根据最后一次计数写了一个查询来重新设置.但是一次如何做10个表.

declare @last int
select @last=max(empid) from Table_1
DBCC CHECKIDENT (Table_1, RESEED, @last)
Run Code Online (Sandbox Code Playgroud)

但如何处理超过10个表或更多表...根据最后一次计数一次性重新播种

ssa*_*ndo 6

遍历所需的表,然后按表运行上述命令.

您必须动态构建SQL语句.

例如,对于SQL Server 2008 R2(您没有指定使用的内容),这可以解决问题:

DECLARE @tname SYSNAME, -- Will hold each table name
    @sname SYSNAME,     -- Will hold each table's schema name
    @idcol SYSNAME,     -- Will hold the name of identity column of each table
    @sql NVARCHAR(4000) -- To build each dynamic SQL statement

-- Declare a cursor to iterate through all table and schema names
-- of current database.
-- Add a WHERE clause here if needed.
DECLARE idtables CURSOR FOR
    SELECT name, SCHEMA_NAME(schema_id)
        FROM sys.tables

OPEN idtables

-- Fetch first table and schema name into the corresponding variables
FETCH NEXT FROM idtables INTO @tname, @sname
WHILE @@FETCH_STATUS = 0
BEGIN
    -- Ensure no dirty values if table has no identity column
    SET @idcol = NULL
    -- Build 1st statement.
    -- Objective: get identity column name, if any.
    SET @sql = 'SELECT @idcolname = name
        FROM sys.columns
        WHERE object_id = OBJECT_ID(''' + @sname + '.' + @tname + ''')
            AND is_identity = 1'
    -- Run the statement and store the result into @idcol
    EXEC sp_executesql @sql,
                       N'@idcolname sysname OUTPUT',
                       @idcolname = @idcol OUTPUT
    IF @idcol IS NOT NULL
    BEGIN
        -- Time for the 2nd statement.
        -- Objective: find the maximum identity value and reseed the table.
        SET @sql = 'DECLARE @lastid int;
            SELECT @lastid = MAX(' + @idcol + ')
                FROM [' + @sname + '].[' + @tname + '];
            IF @lastid IS NOT NULL
                DBCC CHECKIDENT (''' + @sname + '.' + @tname + ''', RESEED, @lastid)'
        EXEC SP_EXECUTESQL @sql
    END
    FETCH NEXT FROM idtables INTO @tname, @sname
END

CLOSE idtables
DEALLOCATE idtables
Run Code Online (Sandbox Code Playgroud)