SQL Compare varchar variable with another varchar variable

后端 未结 2 1733
无人共我
无人共我 2021-01-25 07:27

I have a Table name lines which has BillId (int) and LineReference (Varchar(100) as two columns. Each billid has LineReference value. However, value in the LineReference might n

2条回答
  •  感动是毒
    2021-01-25 08:16

    --Create temp table and inserting data:
    DECLARE @BillsRefs TABLE (
        BillId int, 
        LineReference nvarchar(100)
    )
    
    INSERT INTO @BillsRefs VALUES
    (100,      '1,2,'),
    (100,      '1,2,40,34'),
    (100,      '1'),
    (100,      '12')
    
    --Declare variables
    DECLARE @iCountRef varchar(100) = '1,2,3',
            @xml xml, @iXml xml
    
    --Convert @iCountRef in XML
    SELECT @iXml = CAST('' + REPLACE(@iCountRef,',','') + '' as xml)
    
    --@iXml:
    --1
    --2
    --3
    
    --Convert table with data in XML
    SELECT @xml = (
    SELECT CAST('' + REPLACE(LineReference,',','') + '' as xml) 
    FROM @BillsRefs
    FOR XML PATH('')
    )
    --@xml:
    --
    --  1
    --  2
    --  
    --
    --
    --  1
    --  2
    --  40
    --  34
    --
    --
    --  1
    --
    --
    --  12
    --
    
    --Compare values from temp table to @iCountRef
    --we convert string to xml - to convert them intoi tables
    ;WITH final AS (
    SELECT DISTINCT
            t.v.value('../@id','nvarchar(100)') as LineReferenceOld, -- @id to take 'id="1,2,40,34"' from xml above
            CASE WHEN s.g.value('.','int') IS NULL THEN 1 ELSE s.g.value('.','int') END as LineReference 
            -- '.' is used to take value inside closed tags
    FROM @xml.nodes('/s/a') as t(v) --we takes @xml (look above) and play with its nodes 's' (root for each @id) and `a`
    LEFT JOIN @iXml.nodes('/b') as s(g) --we takes @iXml it has only 'b' tags
        ON t.v.value('.','int') = s.g.value('.','int') --here we JOIN both xml by `a` and `b`  tags
    )
    
    --In final table we get this:
    
    --LineReferenceOld  LineReference
    --1,2,              2
    --12                    1
    --1,2,40,34         1
    --1,2,40,34         2
    --1                 1
    --1,2,              1
    
    --Final SELECT
    SELECT c.BillId,
            STUFF((SELECT DISTINCT  ','+CAST(f.LineReference as nvarchar(10))
            FROM final f
            WHERE c.LineReference = f.LineReferenceOld
            FOR XML PATH('')),1,1,'') as LineReference
    FROM @BillsRefs c 
    

    Output:

    BillId  LineReference
    100     1,2
    100     1,2
    100     1
    100     1
    

    If you need to update source table:

    UPDATE c
    SET LineReference = STUFF((SELECT DISTINCT  ','+CAST(f.LineReference as nvarchar(10))
            FROM final f
            WHERE c.LineReference = f.LineReferenceOld
            FOR XML PATH('')),1,1,'')
    FROM @BillsRefs c  
    

提交回复
热议问题