插入

时间:2017-10-11 15:42:52

标签: sql sql-server tsql sql-server-2016

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

我进入存储过程的数据是这个(@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, manufacturer vendor 应该都有一个与我在插入查询中当前具有的值相关联的数字。

换句话说:

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 ,但在 {{1}表中这是一个应该 mLine 的数字。

3

为了实现这一点,我必须在存储过程中修改什么?

2 个答案:

答案 0 :(得分:0)

当然,您可以使用select(您构建所需的连接)而不是固定值来提供insert语句。

而不是

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;

答案 1 :(得分:0)

您可能希望完全参数化查询,并从您的环境表中选择您的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;

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