Sequences.ReseedSequenceBeyondTableValues
Documentation | WideWorldImporters |
Schema | Sequences |
Name | ReseedSequenceBeyondTableValues |
Input/Output
Mode | Name | Data type | Description | |
---|---|---|---|---|
1 | IN | SequenceName | nvarchar(128) | |
2 | IN | SchemaName | nvarchar(128) | |
3 | IN | TableName | nvarchar(128) | |
4 | IN | ColumnName | nvarchar(128) |
Script
CREATE PROCEDURE Sequences.ReseedSequenceBeyondTableValues @SequenceName sysname, @SchemaName sysname, @TableName sysname, @ColumnName sysname AS BEGIN -- Ensures that the next sequence value is above the maximum value of the supplied table column SET NOCOUNT ON; DECLARE @SQL nvarchar(max); DECLARE @CurrentTableMaximumValue bigint; DECLARE @NewSequenceValue bigint; DECLARE @CurrentSequenceMaximumValue bigint = (SELECT CAST(current_value AS bigint) FROM sys.sequences WHERE name = @SequenceName AND SCHEMA_NAME(schema_id) = N'Sequences'); CREATE TABLE #CurrentValue ( CurrentValue bigint ) SET @SQL = N'INSERT #CurrentValue (CurrentValue) SELECT COALESCE(MAX(' + QUOTENAME(@ColumnName) + N'), 0) FROM ' + QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@TableName) + N';'; EXECUTE (@SQL); SET @CurrentTableMaximumValue = (SELECT CurrentValue FROM #CurrentValue); DROP TABLE #CurrentValue; IF @CurrentTableMaximumValue >= @CurrentSequenceMaximumValue BEGIN SET @NewSequenceValue = @CurrentTableMaximumValue + 1; SET @SQL = N'ALTER SEQUENCE Sequences.' + QUOTENAME(@SequenceName) + N' RESTART WITH ' + CAST(@NewSequenceValue AS nvarchar(20)) + N';'; EXECUTE (@SQL); END; END; |
Exported: 2019-02-04 23:04, Last imported: 2018-08-10 09:51