Is it possible to compare comma delimited string in T-SQL without looping?

后端 未结 2 733
迷失自我
迷失自我 2021-02-11 05:34

Let\'s say I have 2 tables where both has column called Brand. The value is comma delimited so for example if one of the table has

ACER,ASUS,HP  
         


        
2条回答
  •  别那么骄傲
    2021-02-11 06:02

    Had the same problem with comparing "," delimited strings

    you can use "XML" to do that and compare the outputs and return the same/different value:

    declare  @TestInput nvarchar(255)
    , @TestInput2 nvarchar(255)
    
    set @TestInput = 'ACER,ASUS,HP'
    set @TestInput2 = 'HP,GIGABYTE'
    
    
    
    ;WITH FirstStringSplit(S1) AS
    (
     SELECT CAST('' + REPLACE(@TestInput,',','') + '' AS XML)
    )
    ,SecondStringSplit(S2) AS
    (
    SELECT CAST('' + REPLACE(@TestInput2,',','') + '' AS XML)
     )
    
     SELECT STUFF(
     (
    SELECT ',' + part1.value('.','nvarchar(max)')
    FROM FirstStringSplit
    CROSS APPLY S1.nodes('/x') AS A(part1)
    WHERE part1.value('.','nvarchar(max)') IN(SELECT B.part2.value('.','nvarchar(max)')
                                                  FROM SecondStringSplit 
                                                  CROSS APPLY S2.nodes('/x') AS B(part2)
                                                  ) 
    FOR XML PATH('')
    ),1,1,'') as [Same Value]
    

    Edit:

    Changed 'Stuff' to 'XML'

提交回复
热议问题