--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('<b>' + REPLACE(@iCountRef,',','</b><b>') + '</b>' as xml)
--@iXml:
--<b>1</b>
--<b>2</b>
--<b>3</b>
--Convert table with data in XML
SELECT @xml = (
SELECT CAST('<s id="'+LineReference+'"><a>' + REPLACE(LineReference,',','</a><a>') + '</a></s>' as xml)
FROM @BillsRefs
FOR XML PATH('')
)
--@xml:
--<s id="1,2,">
-- <a>1</a>
-- <a>2</a>
-- <a />
--</s>
--<s id="1,2,40,34">
-- <a>1</a>
-- <a>2</a>
-- <a>40</a>
-- <a>34</a>
--</s>
--<s id="1">
-- <a>1</a>
--</s>
--<s id="12">
-- <a>12</a>
--</s>
--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
输出:
BillId LineReference
100 1,2
100 1,2
100 1
100 1
如果需要更新源表:
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