Tuesday, January 23, 2018

Transact-SQL: insert into two tables, use newly created values with output clause

Transact-SQL: insert into two tables, use newly created values with output clause

Microsoft SQL

Tables:
Table1 Columns: Id, Name
Table2 Columns: Id2, Surname, Table1Id

Data:
Name: Adam 
Surname: Sandler

Query:

INSERT INTO Table1(Name
OUTPUT inserted.Id, 'Sandler' INTO Table2 (Table1Id, Surname)  
VALUES('Adam');


Query will not work with foreign keys defined. In order to use it with foreign keys you need to switch off constrain check.

f.e.
ALTER TABLE Table2 NOCHECK CONSTRAINT ALL
GO

Query

ALTER TABLE Table2 CHECK CONSTRAINT ALL
GO

No comments:

Post a Comment

Problem with database open ORA-19804, ORA-19809, ORA-03113

1. Try to login to database with SYS AS SYSDBA user. If the instance is idle, run the startup command. 2. If ORA-03113 occured, check the la...