【发布时间】:2014-10-28 12:36:23
【问题描述】:
我正在编写一个从多个外部系统导入配置数据的应用程序。为了将用户数据与导入的数据分离,您可以使用中间表。为便于论证,下表进行了简化。
-
表
[connection](不包括其他表引用的通用连接信息) -
table
[importConfig](来自外部系统之一的连接配置) -
表
[connectionImportConfig](中间表,链接[connection]和[importConfig]
对于 [importConfig] 中的每个连接,我想在 [connection] 中创建一个带有标识列的行。然后我想在 [connectionImportConfig] 中插入来自 [connection] 的新 ID 和来自 [importConfig] 的标识符。
约束:我不想使用光标。必须是基于集合的解决方案。
我在 stackoverflow 上找到的示例不是基于集合的,或者我发现它们由于其他原因不适用。
T-SQL Insert into multiple linked tables using a condition and without using a cursor(对多行无效,使用
@@IDENTITY)How to perform INSERT/UPDATE to Linking (Join) table which has FKs to IDENTITY PKs(对多行无效。不告诉如何将标识值与我要插入的原始数据连接起来)
我已经尝试了很多,但我不得不将新 ID 插入 connectionImportConfig
-- Test tables&data (stripped down version)
CREATE TABLE connection (ConnectionID int identity(1,1) NOT NULL, comment nvarchar(max) null)
CREATE TABLE connectionImportConfig(connectionID int NOT NULL, ConfigCode nvarchar(50) NOT NULL)
CREATE TABLE importConfig (ConfigCode nvarchar(50) NOT NULL)
DECLARE @MyConnection table (ConnectionID int not null);
insert into importConfig values ('a')
insert into importConfig values ('b')
insert into importConfig values ('c')
-- Insert into PK-table creating the IDs
INSERT INTO connection (comment)
OUTPUT INSERTED.ConnectionID INTO @MyConnection
SELECT * from importConfig
-- How do I insert the new IDs together with the ConfigCode? 1 has to be replaced with the ID.
-- JOIN doesn't seem to work because there is no join condition to use
INSERT INTO connectionImportConfig (connectionID, ConfigCode)
SELECT 1, ConfigCode FROM ImportConfig
select * from @MyConnection
select * from connectionImportConfig
-- Cleanup
DROP TABLE importConfig;
DROP TABLE connection;
DROP table connectionImportConfig;
【问题讨论】:
-
您是否阅读过this answer 关于使用
MERGE命令的内容?OUTPUT功能可以将数据加载到一个表中,然后将该表的标识添加到现有数据中并将其插入到另一个表中。我已经收藏了一段时间,并在几张桥牌桌上愉快地使用它。 -
是的,成功了!非常感谢。我以前从未使用过 MERGE 命令...
标签: sql sql-server tsql