根据其他表数据插入多个表

时间:2018-06-01 08:57:20

标签: sql sql-server sql-server-2008

我需要循环遍历表组织并在User中插入新记录,并根据我需要插入到UserProductMapping,UserGroups表中的新创建的用户ID

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)

我需要动态地将Organisationid和Code传递给User表以循环并在用户详细信息失效后在用户中插入新记录我必须使用userid插入子表。

以便根据组织插入用户表:

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

1 个答案:

答案 0 :(得分:2)

正如EzLo所提到的,输出是你的朋友,用于检索插入的身份值:

-- 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)