将所有序列的序列更改为具有最大id的所有列

时间:2014-08-29 10:31:48

标签: sql sql-server tsql sequence

我正在尝试创建一个存储过程,动态重新启动一个特定模式中的所有序列,每个表的最大值为1列。

这样的事情:

alter sequence @schema.@sequence 
   restart with 
     select max(@column) 
     from @table

我试过了:

SELECT 
    t.name, c.name 
FROM 
    sys.tables t         
INNER JOIN 
    sys.all_columns c  ON c.object_id = t.object_id          
INNER JOIN 
    sys.schemas s ON s.schema_id  = t.schema_id         
WHERE 
    t.name = @table         
    AND c.name = @column        
    AND s.name = @schema  -- to find the table with column the sequence is used

SET @sql_max = 'SELECT MAX(' + @column + ') FROM ' + @table 

--to find the max value to restart the sequence
SET @sql_text = 'ALTER SEQUENCE ' + @schema + '.' + @sequence
          + ' RESTART WITH ' + @start_value
          + ' INCREMENT BY 1
              MINVALUE 0
              MAXVALUE 9223372036854775807
              CACHE  100000;';
-- to restart the sequence with max value I currently selected

我不知道如何为每个表和列设置@start_value

1 个答案:

答案 0 :(得分:0)

简单的 SQL 就能搞定

GO
declare @seq varchar(max);
DECLARE @Sql varchar(max)
SET @seq = (select max(id) from table_name) + 1;
Set @sql = 'ALTER SEQUENCE sequence_name RESTART WITH ' + @seq  
EXEC (@Sql)
GO