Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a row with every column except identity column (SQL Server 2005)

My code:

SELECT * INTO #t FROM CTABLE WHERE CID = @cid   --get data, put into a temp table


ALTER TABLE #t
DROP COLUMN CID       -- remove primary key column CID


INSERT INTO CTABLE SELECT * FROM #t   -- insert record to table
DROP TABLE #t                                -- drop temp table

The error is:

Msg 8101,
An explicit value for the identity column in table 'CTABLE' can only 
be specified when a column list is used and IDENTITY_INSERT is ON.

And I did set

SET IDENTITY_INSERT CTABLE OFF
GO
like image 743
Seth Avatar asked Aug 04 '11 23:08

Seth


People also ask

How do I copy and paste a row in SQL Server?

Using SQL Server Management StudioClick the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy. Click the tab for the table into which you want to copy the columns. Select the column you want to follow the inserted columns and, from the Edit menu, click Paste.

Can we drop identity column?

These are the restrictions for dropping an IDENTITY column: If sp_dboption “identity in nonunique index” is turned on in the database, you must first drop all indexes, then drop the IDENTITY column, and then re-create the indexes.

Can we insert a row for identity column?

The system generates an IDENTITY column value when the keyword DEFAULT is used as the insert_clause for the IDENTITY column.


2 Answers

Try this:

SELECT * INTO #t FROM CTABLE WHERE CID = @cid
ALTER TABLE #t
DROP COLUMN CID

INSERT CTABLE --Notice that INTO is removed here.
SELECT top(1) * FROM #t
DROP TABLE #t

Test Script(Tested in SQL 2005):

CREATE TABLE #TestIDNT
(
    ID INT IDENTITY(1,1) PRIMARY KEY,
    TITLE   VARCHAR(20)
)

INSERT #TestIDNT
SELECT 'Cybenate'
like image 186
Chandu Avatar answered Sep 19 '22 21:09

Chandu


If using SQL Server Management Studio and your problems you have too many fields to type them all out except the identity column, then right click on the table and click "Script table as" / "Select To" / "New Query Window".

This will provide a list of fields that you can copy & paste into your own query and then just remove the identity column.

like image 28
colmde Avatar answered Sep 20 '22 21:09

colmde