sql - How to add data to two tables linked via a foreign key? -
If I have 2 tables, they are called Table A and Tableby. TableB has a foreign key that reflects the table Now I have to add data to both the table and the table for the given scenario. To do this I need to first insert the data in the table, then find and retrieve the last inserted primary key of the table and use it as a foreign key value in tablebill. I then put the value in tablebine. It takes a bit more to do a lot of work to include 1 group of data, how do I get it and how? If possible please provide me the SQL statement for SQL Server 2005.
It says correctly that you SCOPE_IDENTITY ()
, or if you use the INSERT / OUTPUT syntax, then you can do set-based operation, and then can already be included in the set of outputs - for example, here we only Insert 1 (each) in "real" tables:
/ * drop table STAGE_A drop table STAGE_B drop lock Create a table STAGE_B (CustomerKey varchar (10), ORDERNUMBER varchar (100)) Table A (ID not integer NULL) Identity (51,1) Primary Key, Create CustomerKey varchar (10), name varchar (100)) Table B (ID integer no NULL identity (1123.1) Primary key, customer ID integer, ORDERNUMBER varchar (100)) Add Tables B Alternate Key (Customer ID) A (ID Reference); Insert STAGE_A values ('foo', 'foo corp') Insert STAGE_A values ('bar', 'bar industries') Insert STAGE_B values ('foo', '12345') STAGE_B values ('foo', '23456') Insert STAGE_B values ('Bar', '34567') Table @CustMap Announcement (CustomerKey varchar (10), id int no NULL) Insert A (CustomerKey, Name) output INSERTED.CustomerKey, INSERTED.Id @ Select the CustMap Selection CustomerKey, STAGE_A Inserted B (Customer ID, ORDERNUMBER) by name, map.Id, b.OrderNumber STAGE_B map map.CustomerKey = b.Custo Choose MerKey * @CustMap Join one by selecting * B to
Comments
Post a Comment