Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

T-SQL Creates a Table with Primary Keys

$
0
0

Hello I wan to create a new table based on another one and create primary keys as well.

Currently this is how I'm doing it. Table B has no primary keys defined. But I would like to create them in table A. Is there a way using this select top 0 statement to do that? Or do I need to do an ALTER TABLE after I created tableA?

Thanks

select TOP 0 * INTO [tableA] FROM [tableB]

The short answer is NO. SELECT INTO will always create a HEAP table and, according to Books Online :

Indexes, constraints, and triggers defined in the source table are not transferred to the new table, nor can they be specified in the SELECT...INTO statement. If these objects are required, you must create them after executing the SELECT...INTO statement.

So, after executing SELECT INTO you need to execute an ALTER TABLE or CREATE UNIQUE INDEX in order to add a primary key.

Also, if dbo.TableB does not already have an IDENTITY column (or if it does and you want to leave it out for some reason), and you need to create an artificial primary key column (rather than use an existing column in dbo.TableB to serve as the new primary key), you could use the IDENTITY function to create a candidate key column. But you still have to add the constraint to TableA after the fact to make it a primary key, since just the IDENTITY function/property alone does not make it so.

-- This statement will create a HEAP table SELECT Col1, Col2, IDENTITY(INT,1,1) Col3 INTO dbo.MyTable FROM dbo.AnotherTable; -- This statement will create a clustered PK ALTER TABLE dbo.MyTable ADD CONSTRAINT PK_MyTable_Col3 PRIMARY KEY (Col3);


Viewing all articles
Browse latest Browse all 3160

Trending Articles