Skip to content

Instantly share code, notes, and snippets.

@RickyLin
Created April 17, 2021 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickyLin/d6ec25efa95f8cbc64c20a7a3d0d3ee6 to your computer and use it in GitHub Desktop.
Save RickyLin/d6ec25efa95f8cbc64c20a7a3d0d3ee6 to your computer and use it in GitHub Desktop.
Generate and run "insert into ... select ... from" statement for a table.
CREATE PROCEDURE [dbo].[spDuplicateEntryWithIdentityValue]
@TableName NVARCHAR(128),
@IdentityColumnName NVARCHAR(128), -- the name of auto-increasing column
@CurrentIdentityValue INT,
@NewIdentityValue INT OUTPUT
AS
DECLARE @ColumnNames NVARCHAR(MAX)
SELECT @ColumnNames = STRING_AGG(N'[' + COLUMN_NAME + N']', N', ')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND COLUMN_NAME <> @IdentityColumnName
DECLARE @InsertStmt NVARCHAR(MAX)
SET @InsertStmt = N'INSERT INTO ' + @TableName + N'
(' + @ColumnNames + N')
SELECT ' + @ColumnNames + N'
FROM ' + @TableName + N'
WHERE ' + @IdentityColumnName + N' = @Id
SET @NewId = SCOPE_IDENTITY()'
PRINT @insertstmt
EXEC sp_executesql @InsertStmt, N'@Id INT, @NewId INT OUTPUT', @Id = @CurrentIdentityValue, @NewId = @NewIdentityValue OUTPUT
GO
/* Example:
DECLARE @MyTableId INT
EXEC spDuplicateEntryWithIdentityValue @TableName = N'MyTable', @IdentityColumnName = N'MyTableId', @CurrentIdentityValue = 123
, @NewIdentityValue = @MyTableId OUTPUT
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment