用基于集合的操作替换循环

时间:2014-09-09 20:40:45

标签: sql-server

我知道我可能会执行Row-By-Arduous-Row操作太多了。是否有适当的替代以下循环:

DECLARE @clientId int;
DECLARE @enabledClients TABLE(id int); --Some clients will have this setting enabled by default
DECLARE @enabled nvarchar(10);

SET @clientId = (SELECT MIN(clientId) FROM dbo.Client);

INSERT INTO @enabledClients (id) SELECT [id] FROM dbo.Client WHERE name IN ('FOO', 'BAR');

WHILE @clientId IS NOT NULL
BEGIN
    SET @enabled = ISNULL((SELECT 'true' from @enabledClients where id = @clientId), 'false');
     MERGE INTO [dbo].[ClientSetting] AS Target
        USING (VALUES('EnableReports', @enabled)) AS SOURCE ([Key], [Value])
        ON (Target.[clientId] = @clientId AND Target.[Key] = Source.[Key])
    WHEN NOT MATCHED THEN
        INSERT ([ClientId], [Key], [Value])
        VALUES (@clientId, SOURCE.[Key], SOURCE.[Value])
    SET @clientId = (SELECT MIN(clientId) FROM dbo.Client WHERE clientId > @clientId);
END

1 个答案:

答案 0 :(得分:0)

如果您想开始使用基于集合的操作,请首先尝试创建一个SELECT语句,该语句将返回需要插入的行集。

INSERT INTO [dbo].[ClientSetting]([ClientId], [Key], [Value])
     SELECT id, 'EnableReports', clientEnabled FROM dbo.Clients
        WHERE not exists (SELECT 1 from [dbo].[ClientSetting] cs
                            WHERE cs.clientid = clients.id)

在这种情况下,您不需要使用merge语句,因为您只使用插入路径。我发明了clientEnabled列,我想有一个标志,而不仅仅是一组已知的已启用的客户端名称。

那有道理吗?