SQL Server 比较过程中 while 条件内的 where 子句中的参数

问题描述 投票:0回答:1

我正在尝试加载带有 while 条件的过程的表。但我无法比较收到的字符串,例如

where
子句中的向量。

我收到

'Canada,Brazil,Germany'
,需要与包含所有国家/地区的
CountryListSource
表进行比较。我正在使用合并来更新或插入目标表(也许另一个条件会更简单)。因此,我的目标表是空的,但是使用参数运行时存储过程不会显示错误,只是运行但不插入任何数据。

exec ProcessString 'Canada,Brazil,Germany'

这是存储过程代码:

CREATE PROCEDURE ProcessString
    @String VARCHAR(MAX)
AS
BEGIN
    DECLARE @Array INT
    DECLARE @Aux VARCHAR(MAX)
    
    SET @Array = CHARINDEX(',', @String)
    
    WHILE @Array > 0
    BEGIN
        SET @Aux = LEFT(@String, @Array - 1)
        
          ;WITH cte AS
          (
              SELECT DISTINCT
                  cl.Country, 'N/A' AS CountryISOCode, 2 AS UserId
              FROM
                  [dbo].[CountryListSource] AS cl
              WHERE
                  1 = 1
                  AND cl.City = @String
          )
          MERGE INTO [dbo].[CountryListSourceTarget] AS target
          USING cte AS source ON source.Country = target.Country 

          -- Update
          WHEN MATCHED AND (NOT EXISTS(SELECT target.Country, target.CountryISOCode, target.UserId
                                       INTERSECT
                                       SELECT source.Country, source.CountryISOCode, source.UserId
                                      )) 
              THEN UPDATE
                   SET target.UserId = source.UserId,
                       target.Country = source.Country,
                       target.CountryISOCode = source.CountryISOCode, 
                       target.InsertDate = target.InsertDate,
                       target.UpdateDate = GETDATE()
          -- Insert
          WHEN NOT MATCHED BY TARGET
              THEN
                  INSERT (UserId, Country, CountryISOCode, InsertDate, UpdateDate)
                  VALUES (source.UserId, source.Country,
                          source.CountryISOCode, GETDATE(),
                          '1900-01-01 00:00:00.000');
        PRINT 'Processing string: ' + @Aux
        
        SET @String = SUBSTRING(@String, @Array + 1, LEN(@String) - @Array)
        SET @Array = CHARINDEX(',', @String)
    END
    
    -- Process the last string (or unique without comma)
    PRINT 'Processing string: ' + @String
END
sql-server stored-procedures
1个回答
0
投票

我不知道为什么你认为你需要一个循环。您可以在单个语句中使用

STRING_SPLIT

您还应该添加一个

SERIALIZABLE
锁定提示。

WITH cte AS
(
    SELECT
        cl.Country, 'N/A' AS CountryISOCode, 2 AS UserId
    FROM
        STRING_SPLIT(@String, ',') s
    JOIN dbo.CountryListSource AS cl ON cl.City = s.value
    GROUP BY
        c.Country
)
MERGE INTO dbo.CountryListSourceTarget AS target WITH (SERIALIZABLE)
USING cte AS source ON source.Country = target.Country 
.....

老实说,无论如何,您可能最好使用表值参数,而不是拆分字符串。

© www.soinside.com 2019 - 2024. All rights reserved.