[英]Adding data to multiple tables from multiple #tables in SQL Server with SCOPE_IDENTITY
我有两个包含数千条记录的临时表。 表结构如下。
#TmpCity
ID | CityName
1 | test
#Location
ID | LocationName
1 | abc
2 | xyz
3 | etc
我有2个具有相同模式的物理表City和Location ,其中Location Table包含一个外键CityID,它将自动递增City表的主键。 我需要将数据从#tmpCity添加到城市表,并将#tmpLocation添加到位置表。
我无法对插入的每个城市记录使用INSERT INTO ,因为必须记录的大量记录,我想为该城市插入一个带有scopeIdentity的位置记录,我想避免像循环或游标这样的逐行操作。 实现此目标的最佳方法是什么?
INSERT INTO [dbo].[City]([CityName])
Select [CityName] from [dbo].[#TmpCity]
INSERT INTO [dbo].[Location]([CityId],[LocationName])
Select (select TOP(1) tab1.[CityId] from [dbo].[City] as tab1
join [dbo].[#City] as tab2 on tab1.[CityName]=tab2.[CityName]
where tab2.[ID]=loc.[CityId]),loc.[LocationName] from [dbo].[#Location] as loc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.