Insert into multiple tables based on the other tab

2019-08-20 18:25发布

问题:

I need to loop through table Organisation and insert new record in User and based on the newly created userid I need to insert into UserProductMapping,UserGroups tables

Select Code,Organisationid from organisation 

INSERT INTO User(userlogin,Organisationid,emailaddress,username,userpassword)
VALUES('AGT'+ Code, organisationid,'test@gmail.com','User'+ Code,'123')


INSERT INTO UserProductMapping (UserID, ProductID) VALUES (@userid, '11')
INSERT INTO UserProductMapping (UserID, ProductID) VALUES (@userid, '22')
INSERT INTO UserProductMapping (UserID, ProductID) VALUES (@userid, '33')
INSERT INTO UserProductMapping (UserID, ProductID) VALUES (@userid, '44')
INSERT INTO UserProductMapping (UserID, ProductID) VALUES (@userid, '55')

INSERT UserGroups values (@userid, 1)
INSERT UserGroups values (@userid, 3)

I need to dynamically pass the Organisationid and Code to the User table to loop through and insert new record in user after inerting user details I have to use userid to insert into child table.

in order to insert into user table based on organisation :

INSERT INTO User (userlogin, Organisationid, emailaddress, username, userpassword)
SELECT 'AGT' + Code, organisationid, 'test@gmail.com', 'User' + Code, '123'
FROM organisation;

回答1:

As EzLo mentioned, output is your friend for retrieving identity values inserted:

-- use a table _temp_org_records for output
if object_id('_temp_org_records') is not null drop table _temp_org_records;

-- create table with correct column datatypes
select top 0 UserID
into _temp_org_records
from UserProductMapping


INSERT INTO User (userlogin, Organisationid, emailaddress, username, userpassword)
OUTPUT inserted.UserID INTO _temp_org_records --all USerIDs will be saved into _temp_org_records
    SELECT 'AGT' + Code, organisationid, 'test@gmail.com', 'User' + Code, '123'
    FROM organisation;

INSERT INTO UserProductMapping (UserID, ProductID) 
    SELECT t.UserID, productid.value
    FROM 
        _temp_org_records t
        cross join (values ('11'),('22'),('33'),('44'),('55')) as productid(value)

INSERT UserGroups 
    SELECT t.UserID, UserGroup.value
    FROM 
        _temp_org_records t
        cross join (values ('1'),('3')) as UserGroup(value)