Insert from temp table to a table with identity column - sql-server

I'm grabbing some rows from a table, manipulating them in a temp table, and then looking to insert them as new rows into my original table.
However, I'm running into an issue with the identity column, even when I don't have the identity column on my temp table. The identity column is an auto-incrementing int.
This seems like a simple thing I'm way overthinking.
select top 0 *
into #TestTable
from OriginalTable;
...
--insert and manipulate records
...
ALTER TABLE #TestTable
DROP COLUMN MyIdentityColumn;
DECLARE #InsertedRows TABLE (NewSeqNum INT);
INSERT INTO OriginalTable
OUTPUT MyIdentityColumn INTO #InsertedRows(NewSeqNum)
SELECT * FROM #TestTable
but I get this error:
An explicit value for the identity column in table 'OriginalTable' can only be specified when a column list is used and IDENTITY_INSERT is ON.
I absolutely do not want to set an explicit value, I want it to insert and give me the new identity (via #InsertedRows)

If you don't want to keep the id of inserted records, then you need to specify all your columns but the id column in the select. As general good practice, dont select *, always specify the columns you want to retrieve-insert.
INSERT INTO OriginalTable (col1, col2, col3...)
OUTPUT MyIdentityColumn INTO #InsertedRows(NewSeqNum)
SELECT (col1, col2, col3...) FROM #TestTable

If I'm understanding you, I think your problem is that you're trying to insert '*' into the original table - which means all of your columns from the temp table. Including your ID column (which you don't want to insert, because you're wanting it to auto-generate.)
Instead, I'd suggest doing something like this:
Select [ColumnB],[ColumnC],[ColumnD],[Etc] into your temp table
Select [ColumnB],[ColumnC],[ColumnD],[Etc] into your original table.
... aka, spell out the columns explicitly, and omit the Identity column.

Related

Insert columns from another table

I'm not sure if I'm going the right way about this but I want to create another table with an auto increment ID.
I created another table but how do I add the columns from the first table into the new table and an auto increment ID?
Basically this is the same as copying any table into another table, just be sure not to specify the ID column.
INSERT INTO newTable (col1, col2, col3)
SELECT column1, column2, column3
FROM oldTable
See also: Copy data into another table

mssql - Insert multiple rows back into original table from temporary table

If I select multiple rows into temporary table, how to insert these rows back into the same original table?
For example:
Select * into #temp_table from mytable where id=1 - will provide 4 rows for my temp_table.
Now I would like to insert these 4 rows back into the same original table (mytable) and If I will execute the same select statement after insert, I want to see 8 rows in results with just unique id.
What is the best and easiest way to do it? Maybe temporary table isn't good idea at all.
If you just want to add everything straight from the temporary table back into myTable, then you can do it simply by:
Insert into mytable
Select * from #temp_table
If you need to reuse the temporary table, then remember to clear this before adding the next lot of entries:
delete from #temp_table
Of course, it would be easier skipping the temporary table part all together if you just want to add some more entries from one table back into itself:
Insert into mytable
Select * from mytable where id=1
One thing to note here, this won't work if you have an auto incrementing identity column (as a Primary Key for example) in mytable, as select * will try to insert the ID again into the table which isn't allowed (must be unique). therefor, instead of using select *, you are best specifying the column names. This example would be better:
Insert into mytable (column1Name, column2Name)
Select column1Name, column2Name from mytable where id=1
Hope this is of some help. Good luck.

How to create a SQL Server table with a column and its values to be generated automatically as a GUID

I need to design a table in SQL Server having some columns, one of these columns (ID column and use sequential uniqueidentifier) should automatically populate its data when inserting other column data.
The values of the ID column should be generated automatically when insertion happens.
Please help me to do this, any help is appreciated.
NB: I am new to this step by step approach will be more helpful
Just create a table with a column ID of datatype uniqueidentifier and set it's default value to newsequentialid():
Then, when you go insert rows into that table, just omit the ID column from the list of columns you're inserted values into:
INSERT INTO dbo.YourTable(ColA, ColB, ....., ColX)
VALUES(.., .. ,. ...)
If you don't explicitly insert a value into ID, the default specification (newsequentialid()) will be used .
As per Marc_s's comment, you should use NEWSEQUENTIALID()
CREATE TABLE myTable (ColumnA uniqueidentifier DEFAULT NEWSEQUENTIALID());
See NEWSEQUENTIALID (Transact-SQL)

Get values of IDENTITY values when inserting multiple rows into a table having instead of trigger

I'm inserting several rows into a table A which has an instead of insert trigger and an identity column.
Then I need to insert so many rows in a table B where each row hold a reference to the rows inserted in A.
The problem is, I can't use the output clause on A since, the identity will not be set (due to the trigger).
I know for one row I could use ##identity as long as the insertion of rows in A is the last insertion statement inside the trigger, but here I'm talking about multiple rows.
How can I achieve this?
I used code like this ( You CAN use table variable in OUTPUT clause )
declare #T table (requestID int);
INSERT <tableA> (<fields>)
OUTPUT inserted.RequestID into #T
VALUES( <fieldValues1> ),( <fieldValues2> ) ;
Insert <tableB> (ID) select RequestID from #T;

What is the use of OUTPUT clause in sql server

What is the purpose of the OUTPUT clause? I have gone through the MSDN documentation for the OUTPUT clause, which includes the following example:
DELETE FROM dbo.table1
OUTPUT DELETED.* INTO #MyTableVar
WHERE id = 4 OR id = 2;
From the above query, it seems that deleted records are saved in some magic table called deleted, and the query will load those records into table called MyTableVar from the magic deleted table. .
I still do not understand the purpose of the OUTPUT clause usage.
As another SQL example:
USE AdventureWorks2012;
GO
DECLARE #MyTableVar table( NewScrapReasonID smallint,
Name varchar(50),
ModifiedDate datetime);
INSERT Production.ScrapReason
OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
INTO #MyTableVar
VALUES (N'Operator error', GETDATE());
--Display the result set of the table variable.
SELECT NewScrapReasonID, Name, ModifiedDate FROM #MyTableVar;
--Display the result set of the table.
SELECT ScrapReasonID, Name, ModifiedDate
FROM Production.ScrapReason;
GO
What is this actually doing? Can anyone explain what this clause is doing with an easy example?
UPDATE with non-functioning example:
create proc test
as
CREATE TABLE dbo.table1
(
id INT,
employee VARCHAR(32)
)
go
INSERT INTO dbo.table1 VALUES
(1, 'Fred')
,(2, 'Tom')
,(3, 'Sally')
,(4, 'Alice')
delete from table1
select * from deleted
This gives me an error when I run it, because it can't see the deleted table.
The general purpose of this clause is to capture the changes made to your data without an additional query, which would introduce locking and blocking issues. Example:
DELETE FROM X WHERE Name = 'Foo'
You want to know which IDs were deleted. You can do this naively like this:
SELECT ID FROM X WHERE Name = 'Foo'
DELETE FROM X WHERE Name = 'Foo'
But these selected IDs are unreliable unless you are running in a transaction with isolation level SERIALIZABLE which is usually not the case. Someone else can add, delete or change "Foo"-Records between your two statements. So instead you can use the OUTPUT clause and get back exactly and reliably the deleted IDs without any performance or reliability issues.
Another frequent use is to get the value of inserted default values, especially when using identity columns. For a single insert you can do this:
CREATE TABLE X
(
ID INT IDENTITY,
Name VARCHAR(10)
);
INSERT X (Name) VALUES ('Foo')
SELECT SCOPE_IDENTITY()
But SCOPE_IDENTITY() can give you only the last inserted ID. If you do multiple inserts, like
INSERT X (Name) VALUES ('Foo'), ('Bar')
or
INSERT X (Name) SELECT OtherName FROM Y
and you want to know the inserted IDs, you are out of luck. You can try to find them with another SELECT, but you need another unique column to even formulate the query and then you run into the same issues as with the DELETE sample above. So, the OUTPUT clause lets you identify neatly which Names got which IDs.
You will need these IDs for example when creating dependent records with foreign keys. Think "Order" and "OrderDetails" which are linked by an OrderID column with an IDENTITY clause. Again, with a single INSERT you can get away with using SCOPE_IDENTITY() or ##IDENTITY, but when inserting multiple orders at once, you will need OUTPUT.
When you perform Insert/Update/Delete operation on particular table and want to know what rows are affected OR want to log them for audit trail OR you want to use multiple values of affected rows in subsequent sql statements, you can use OUTPUT clause.
For Insert statement, it will have INSERTED table.
For Delete statement, it will have DELETED table. In case of Update DELETED table will contain rows (with old values) before update operation performed.
For Update statement, it will have DELETED and INSERTED tables.
DELETED table will contain rows (with old values) before update operation performed.
INSERTED table will contain rows (with new values) after update operation performed.
USE AdventureWorks2012;
GO
DECLARE #MyTableVar table( NewScrapReasonID smallint,
Name varchar(50),
ModifiedDate datetime);
INSERT Production.ScrapReason
OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
INTO #MyTableVar
VALUES (N'Operator error', GETDATE());
--Display the result set of the table variable.
SELECT NewScrapReasonID, Name, ModifiedDate FROM #MyTableVar;
--Display the result set of the table.
SELECT ScrapReasonID, Name, ModifiedDate
FROM Production.ScrapReason;
Now your query inserts rows in Production.ScrapReason as well as table variable #MyTableVar. Later it selects inserted rows from Production.ScrapReason and #MyTableVar. Thus you can compare both the resultset and it must have identical rows (considering Production.ScrapReason is empty table.)
I hope it makes sense!
Edit:
Inserted/Deleted tables will be available with Insert/Update/Delete statement and not after that. You may want to store those magic table values in db table or temp table.
Without the OUTPUT clause, how would you know which rows were deleted? Your example seems so simple because you already know the Id values, but what if you did this:
DELETE FROM T WHERE SomeColumn LIKE 'SomePattern%'
And you want to find out what was deleted. That's the purpose of the OUTPUT clause.

Resources