sql-server – 插入OUTPUT与子查询表相关
发布时间:2020-12-12 17:00:42 所属栏目:MsSql教程 来源:网络整理
导读:我正在修改数据库的结构.表FinancialInstitution的几列的内容必须转移到表Person中. FinancialInstitution与具有外键的Person链接.每个FinancialInstitution都需要其相应Person的Id.因此,对于插入Person中的每个新行,必须将此新行(IDENTITY)的id复制回相应的F
我正在修改数据库的结构.表FinancialInstitution的几列的内容必须转移到表Person中. FinancialInstitution与具有外键的Person链接.每个FinancialInstitution都需要其相应Person的Id.因此,对于插入Person中的每个新行,必须将此新行(IDENTITY)的id复制回相应的FinancialInstitution行.
这样做的显而易见的方法是迭代的T-SQL代码.但我很想知道是否可以只使用基于集合的操作来完成它. 我想象这样一个请求的内在层次会是这样的: INSERT INTO Person (Street1,Number1,City1,State1,PostCode1,CountryId1,WorkDirectPhone1,Fax1,Email1) OUTPUT inserted.Id,FinancialInstitution.Id SELECT Id,Street,Number,City,[State],PostCode,CountryId,PhoneNumber,Fax,Email FROM FinancialInstitution; 不幸的是,似乎OUTPUT无法以这种方式关联…… 解决方法我猜你可以(ab)使用MERGE.首先创建一个(临时)表:CREATE TABLE tempIDs ( PersonId INT,FinancialInstitutionId INT ) ; 然后MERGE成Person(而不是INSERT),因此您可以使用OUTPUT子句中涉及的表的列: MERGE INTO Person USING FinancialInstitution AS fi ON 1 = 0 WHEN NOT MATCHED THEN INSERT (Street1,...) VALUES (fi.Street,fi.Number,fi.City,...) OUTPUT inserted.Id,fi.Id INTO tempIDs ; 然后使用临时表来更新FinancialInstitution: UPDATE fi SET fi.PersonId = t.PersonId FROM FinancialInstitution AS fi JOIN tempIDs AS t ON fi.Id = t.FinancialInstitutionId ; 测试时间:SQL-Fiddle (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |