栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何复制表以避免在SQL中出现游标?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何复制表以避免在SQL中出现游标?

您可以将output子句与merge语句一起使用,以获取源ID和目标ID之间的映射。

这是您可以测试的一些代码。我使用表变量而不是实际表。

设置样本数据:

-- @A and @B is the source tablesdeclare @A as table(  id int,  FK_A_B int,  name varchar(10))declare @B as table(  id int,  visible bit)-- Sample data in @A and @Binsert into @B values (21, 1),(32, 0)insert into @A values (1, 21, 'n1'),(5, 32, 'n2')-- @C and @D is the target tables with id as identity columnsdeclare @C as table(  id int identity,  FK_C_D int not null,  name varchar(10))declare @D as table(  id int identity,  visible bit)-- Sample data already in @C and @Dinsert into @D values (1),(0)insert into @C values (1, 'x1'),(1, 'x2'),(2, 'x3')

复制数据:

-- The @IdMap is a table that holds the mapping between-- the @B.id and @D.id (@D.id is an identity column)declare @IdMap table(TargetID int, SourceID int)-- Merge from @B to @D.merge @D as D  -- Target tableusing @B as B  -- Source tableon 0=1         -- 0=1 means that there are no matches for mergewhen not matched then  insert (visible) values(visible)    -- Insert to @Doutput inserted.id, B.id into @IdMap; -- Capture the newly created inserted.id and     -- map that to the source (@B.id)-- Add rows to @C from @A with a join to-- @IdMap to get the new id for the FK relationinsert into @C(FK_C_D, name)select I.TargetID, A.name from @A as A  inner join @IdMap as I    on A.FK_A_B = I.SourceID

结果:

select *from @D as D  inner join @C as C    on D.id = C.FK_C_Did          visible id          FK_C_D      name----------- ------- ----------- ----------- ----------11       11x111       21x220       32x331       43n140       54n2


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/431636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号