Get the _skey column name from table and Reset the value of key column to 1 when reaches to max from table on every run of sp

Raj0125 511 Reputation points
2022-05-24T11:09:36.217+00:00

Hi,

I am writing the below stored procedure to get _skey column from all tables present in DBO Schema and reset _skey column to 1 on every run of my storted procudere.

CREATE PROCEDURE sp_reset_1
(
@TableName SYSNAME
, @IdentityColumn SYSNAME
)
AS
BEGIN
DECLARE @SQLCommand NVARCHAR(4000)
SET @SQLCommand = N'
DECLARE @MaxID INT;
SET @MaxID = COALESCE((SELECT MAX(' + QUOTENAME(@IdentityColumn) + ') FROM ' + QUOTENAME(@TableName) + '), 1);
DBCC CHECKIDENT(' + QUOTENAME(@TableName, '''') + ', RESEED, @MaxID);
';

--EXEC sp_executesql @SQLCommand;
END

Please suggest how to write/modify the above sp to get the _skey column from all tables dynmically having DBO Scheama.kindly suggest.

Thanks

Azure SQL Database
0 comments No comments
{count} votes

Accepted answer
  1. Anurag Sharma 17,571 Reputation points
    2022-05-25T08:00:13.757+00:00

    Hi @Raj0125 , welcome to Microsoft Q&A forum.

    Please find the Stored Procedure below:

    //Updated the SP as per suggestion

    CREATE PROCEDURE sp_ResetIdentityMax  
     AS  
     DECLARE @Table TABLE  
     (  
     TableName VARCHAR(50),  
     Id int identity(1,1)  
     )  
          
     --Getting only identity columns from all tables with dbo schema. You can add column name as well in where condition if you would like to  
     INSERT INTO @Table  
     select TABLE_NAME  from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA = 'dbo' and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 and COLUMN_NAME like '%SKey' AND COLUMN_NAME NOT LIKE '%LOAD_SKey' AND COLUMN_NAME NOT LIKE 'GDP%'  
          
     DECLARE @max int, @SQL VARCHAR(MAX) , @TableName VARCHAR(100), @ColumnName varchar(100)  
     DECLARE @id int = 1  
     select @max = MAX(Id) from @Table  
          
     WHILE (@id <= @max)  
     BEGIN  
          
     SELECT @TableName = TableName FROM @Table WHERE Id = @id  
          
     --Resetting the column value to '1' for new records  
     DBCC CHECKIDENT(@TableName, RESEED,0);  
          
     SET @id = @id +1  
     END  
    

    Referenced Article: t-sql for loop to iterate through tables

    Please let me know if this helps or else we can discuss further

    ----------

    If answer helps, you can mark it 'Accept Answer'


0 additional answers

Sort by: Most helpful