Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a row within the same table

Tags:

sql

database

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...

like image 535
sl3dg3 Avatar asked Jun 22 '11 12:06

sl3dg3


People also ask

How do you replicate rows in SQL?

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.

How do I copy data into the same table based on existing data in SQL?

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.


1 Answers

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!

like image 142
sl3dg3 Avatar answered Oct 19 '22 03:10

sl3dg3