We can create a table with the select command as well. General syntax to create a table with the select command is :
SELECT * INTO <YourNewTable> FROM <YourTable>
While using "SELECT * INTO " command we should keep following concepts in mind.
- Identity Columns
- if using simple select operation, new table will inherit the Identity property
- New table will not inherit the Identity property for following cases
- Identity columns are listed more than one time in select list
- Using multiple select operations with UNION or UNION ALL clause
- Identity column is a part of an expression
- If identity column is required in destination table but not available in source result-set you can define your own identity function e.g.
-- -- Step 1. Create a table "Table_1" with identity column (ID) -- CREATE TABLE TABLE_1 (ID INT IDENTITY(1,1) PRIMARY KEY, Name VARCHAR(20)) -- -- Step2. Insert some records --INSERT INTO table_1(Name) values ('Ram'), ('Shyam'), ('Sohan') ---- Step3. (ERROR) Create new table "Table_2" suing "SELECT INTO" statement ---- (try adding your own Id identity ) ---- IT WILL GIVE AN ERROR AS "ID" Column in Source table is already AN IDENTITY COLUMN --SELECT IDENTITY(INT, 1,1) AS MyIdentityId -- , ID AS ExistingId -- , Name --INTO Table_2 --FROM table_1 ---- Step4. (SUCCESS) Create new table "Table_2" using "SELECT INTO" statement ---- try using your own identity column, with expression (cast function) in existing ID column ---- It will successfully get executed with new table "Table_2" having "MyIdentityId" as an Identity column --SELECT IDENTITY(INT, 1,1) AS MyIdentityId -- , CAST(ID AS int) AS ExistingId -- , Name --INTO Table_2 --FROM table_1
- Indexes, constraints & triggers will not get transferred from the source table to destination table If it's required you've to create it explicitly.
- Order by clause doesn't guarantee the data will get inserted in the same order
- If we're using any expression in select statement (e.g. some computation), it doesn't create the computed column into the destination table instead exact data will get inserted
Comments
Post a Comment