如何在CTE中循环每个记录并读取列值

时间:2019-03-29 17:22:58

标签: sql sql-server

我必须在CTE中循环数据,并基于一个列值获取每个记录和处理。

CREATE PROCEDURE [dbo].[sp_saveVmssMapping]
    (@serverTypes INT = 0,
     @vmsses INT = 0,
     @regions INT = 0,
     @countryList VARCHAR)
AS 
    WITH countryTbl AS
    (
        SELECT value 
        FROM STRING_SPLIT(@countryList, ',')
    )
    DECLARE @cnt INT = 0;
    DECLARE @cnt_total INT;
    SET @cnt_total = SELECT COUNT(*) FROM countryTbl;

    WHILE @cnt < cnt_total
    BEGIN
        IF NOT EXISTS (SELECT * FROM VmssCountryMapping 
                       WHERE VmssId = @vmsses 
                         AND Country_code = @userName 
                         AND ServerTypeId = @serverTypes)
        BEGIN
            INSERT INTO VmssCountryMapping (VmssId, Country_code, ServerTypeId) 
            VALUES (@vmsses, @userName, @serverTypes)
        END
        SET @cnt = @cnt + 1;
    END

在这里,我创建了一个CTE,在其中添加了逗号分隔的记录。现在,我将遍历每条记录并处理与查询匹配的插入。

1 个答案:

答案 0 :(得分:1)

无需循环结果,您只需一次插入所有内容即可。

CREATE PROCEDURE [dbo].[sp_saveVmssMapping]
(
    @serverTypes INT = 0,
    @vmsses INT = 0,
    @regions INT = 0,
    @countryList VARCHAR(AlwaysAssignALength)
)
AS 
with countryTbl as 
(
 SELECT value FROM STRING_SPLIT(@countryList, ',')
)
INSERT INTO VmssCountryMapping (VmssId, Country_code, ServerTypeId) 
SELECT @vmsses, value, @serverTypes 
FROM countryTbl c
WHERE  NOT EXISTS (SELECT * 
                    FROM VmssCountryMapping m
                    WHERE m.VmssId = @vmsses 
                    AND m.Country_code = c.value 
                    AND m.ServerTypeId = @serverTypes);