Created
April 17, 2021 08:52
-
-
Save RickyLin/d6ec25efa95f8cbc64c20a7a3d0d3ee6 to your computer and use it in GitHub Desktop.
Generate and run "insert into ... select ... from" statement for a table.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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