【问题标题】:Insert into multiple tables based on the other table data根据其他表数据插入多个表
【发布时间】:2018-06-01 08:57:19
【问题描述】:

我需要遍历表组织并在用户中插入新记录,并根据我需要插入到 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;

【问题讨论】:

  • 循环并插入新记录 - SQL 不应该在循环中工作,而是在整个数据集中思考。在这种情况下,这意味着生成您想要的数据集,然后将其 inserting 到您的表中。
  • 除了 iamdave 所说的:您是否有一张包含所有需要插入的组织 ID 代码对的表格?
  • inroder 插入用户表我有以下查询更新了问题
  • 使用带有 OUTPUT 子句的 MERGE 来检索插入语句的 UserID 标识值,然后根据需要使用结果插入到其他表中。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多