SQL Server 2016 在插入之前访问其他 table 值

SQL Server 2016 access other table values before Insert into

是否可以在执行 insert into 查询之前执行 JOIN ON xx.xx = xx.xx

我进入存储过程的数据是这样的 (@val1):

network,type,incrementRelease,environment,serviceManagerType,
serviceManagerSubType,description,manufacturer,vendor

上面的值 (@val2):

'Force','SW','3','ATT','STORAGE','CHASSIS','details here','Microsoft','REDHAT'

现在查询(存储过程)本身:

INSERT INTO mLine 
   (@val1) 
VALUES 
   (@val2)

现在我需要在插入之前调用 JOIN ON 的原因是目前 environment, serviceManagerType, serviceManagerSubType, manufacturervendor 应该都有一个与它当前在我的插入查询中的值关联的数字。

换句话说:

mLine table:
id  |network |type |....|environment |...
-----------------------------------------
54  |Force   |SW   |....|ATT         |...

environment table:
id |Name
-------- 
1  |Open
2  |Closed
3  |ATT
4  |Unknown
5  |Other

对于上面的示例,environment 发送的值为 ATT 但在table mLine 它应该是 3.

mLine table:
id  |network |type |....|environment |...
-----------------------------------------
54  |Force   |SW   |....|3           |...

为了完成此操作,我必须在存储过程中修改哪些内容?

当然,您可以为插入语句提供 select(您在其中构建所需的连接)而不是固定值。

而不是

INSERT INTO mLine (field list) 
VALUES (values list)

做:

INSERT INTO mLine (environment)
SELECT id FROM environment WHERE Name = @environment

为了从多个表中检索数据,SELECT 可以根据需要复杂化。

更新:考虑到您没有@environment 值,因为它打包在@val2 参数上,您首先需要解包该参数,提取每个单独的值。您可以使用 STRING_SPLIT 函数执行此操作。

declare @network varchar(20);
declare @type varchar(20);
declare @incrementRelease varchar(20);
declare @environment varchar(20);

select @network = value from string_split(@val2, ',') fetch next 1 row only;
select @type = value from string_split(@val2, ',') offset 1 rows fetch next 1 row only;
select @incrementRelease = value from string_split(@val2, ',') offset 2 rows fetch next 1 row only;
select @environment = value from string_split(@val2, ',') offset 3 rows fetch next 1 row only;

您可能希望完全参数化您的查询和 select 来自您环境 table 的 ID 值。

INSERT INTO mLine(Network, type, incrementRelease, environment, serviceManagerType, serviceManagerSubType, description, manufacturer, vendor)
SELECT @Network, @type, @incrementRelease, E.ID, @serviceManagerType, @serviceManagerSubType, @description, @manufacturer, @vendor
FROM dbo.environment E
WHERE E.Name = @environment;

编辑:根据评论更新了答案。