Given following SQL (MS SQL 2008):
SET IDENTITY_INSERT MyTable ON
GO
INSERT INTO MyTable
SELECT * FROM MyTable
WHERE Id = @SomeId
GO
SET IDENTITY_INSERT MyTable OFF
This results in:
An explicit value for the identity column in table 'MyTable' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Well, do I really need to define a column list? Is there no way to keep it generic? E.g. if a developer adds a column later on, this column won't make it into this routine, and it even will fail if null is not allowed...
To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.
A simple way to do it would be to first load it up into a temp table, make the changes, and then insert it back into the main table.
Well, there is actually a more generic way, this works well without knowing the columns:
DECLARE @Tablename NVARCHAR(255) = 'MyTable'
DECLARE @IdColumn NVARCHAR(255) = 'MyTableId' -- Primarykey-Column, will be ignored
DECLARE @IdToCopyFrom VARCHAR(255) = '33' -- Copy from this ID
DECLARE @ColName NVARCHAR(255)
DECLARE @SQL NVARCHAR(MAX) = ''
DECLARE Table_Cursor CURSOR FOR
SELECT [B].[Name]
FROM SYSOBJECTS AS [A], SYSCOLUMNS AS [B]
WHERE [A].[ID] = [B].[ID] AND A.name = @Tablename
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @ColName
WHILE (@@FETCH_STATUS = 0)
BEGIN
-- Loop through all columns and link them into the Sql-string (except the PK-column)
DECLARE @SkipComma BIT = 0
IF (@ColName <> @IdColumn)
SET @SQL = @SQL + @ColName
ELSE
SET @SkipComma = 1
FETCH NEXT FROM Table_Cursor INTO @ColName
IF (@SkipComma = 0 AND @@FETCH_STATUS = 0)
SET @SQL = @SQL + ','
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor
SET @SQL = 'INSERT INTO ' + @Tablename + '(' + @SQL + ')' +
' SELECT ' + @SQL + ' FROM ' + @Tablename +
' WHERE ' + @IdColumn + ' = ' + @IdToCopyFrom
PRINT @SQL
EXEC(@SQL)
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With