如何在table(SQL)中多次插入数据

How to insert data multiple times in a table (SQL)

我有3个table如下:

DXBusinessPolicy_Policy

ID Code Name
1 COMBO.2103001 [Giá nền] T9/2020 #1
2 IPTV-0121.002 [Giá nền] T8/2020 #1

DXBusinessPolicy_Service

ID Code Name
1 INT Internet
2 IPTV IPTV
3 CMR Camera
4 FSAFE Fsafe

DXBusinessPolicy_PolicyService

ID PolicyID ServiceID
1 1 1
2 1 2

这是我的存储过程:

CREATE PROCEDURE InsertPolicyService
    @id int,
    @services varchar(1000) //This is Service Name
AS 
BEGIN 
    INSERT INTO dbo.DXBusinessPolicy_PolicyService (PolicyID, ServiceID) 
        SELECT 
            @id,
            (SELECT dbo.DXBusinessPolicy_Service.ID 
             FROM dbo.DXBusinessPolicy_Service
             WHERE dbo.DXBusinessPolicy_Service.Code IN (SELECT VALUE FROM string_split(@services, ',')))
END 



EXEC InsertPolicyService 2, 'FSAFE,CMR'

我想将带有名为 FSAFE 和 CMR 的服务的策略 ID 2 插入 table DXBusinessPolicy_PolicyService。

我试图执行此存储过程,但出现此错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

我的期望是:

DXBusinessPolicy_PolicyService

ID PolicyID ServiceID
1 1 1
2 1 2
3 2 3
4 2 4

您的内部子查询 returns 多个结果,当它是子查询时这是不可能的。但是你不需要那么多查询,只需要一个:

INSERT INTO dbo.DXBusinessPolicy_PolicyService (PolicyID, ServiceID) 
    SELECT @id, dbo.DXBusinessPolicy_Service.ID 
    FROM dbo.DXBusinessPolicy_Service
    WHERE dbo.DXBusinessPolicy_Service.Code IN (
        SELECT VALUE FROM string_split(@services,','))
    );