Sql-server – SQL Server – Copying a key from one table to another

identityprimary-keysql server

In a trigger, I have created a table using SELECT * INTO. I have done that in a specific way, in order to create the table without also creating the identity column that exists in it (let's name this column ID):

SELECT * INTO #ins 
FROM (SELECT * FROM inserted 
      UNION ALL 
      SELECT * FROM inserted WHERE 1 = 0) AS a

The problem is that the new table (#ins) does contain the identity column (which I want it to) but it has not marked is as Primary Key (which is how it was in the original table, and I would like to keep it that way).

I would like to know the easier of the following two:

  1. How could I "read" the primary key from the original table and alter the new one to also add it there? I would like this to be generic, so assume the name of the ID column will be unknown.

or (if easier)

  1. Is there another way to create table #ins from the original, retaining the column "ID" and its definition as primary key, but without it being an IDENTITY one?

EDIT: OK, as stated in a comment below, the task i was trying to achieve can be done in another way, using the primary key from the original table. This makes the question above rather pointless.

Best Answer

For permanent reused code like this, you really should be explicitly defining your temporary table definitions. If you are looking for an easy way to do that, please see below. I'll also include information on your actual question.

Easy way to generate table definition:

  • locate the object in object explorer
  • right click on it and select "script --> create table --> to SSMS window"

This should generate a new SSMS window with the table you selected scripted there. Depending on your options, you will have indexes as well at the bottom.

To make it a temporary table, just change the name of the table.

Remove IDENTITY

Locate the identity column and remove the identity definition more than likely "IDENTITY(1,1)".

Example:

CREATE TABLE #INS
(
MyIdentityID INT NOT NULL PRIMARY KEY
, MyValue VARCHAR(100) NOT NULL
)

Please note, this is a simple and straightforward method that directly answers your question. Any use of temporary tables in triggers makes me suspicious and I would like to know the full business reason behind it; it's possible that a better solution exists.