我在SQL Server 2008 db中有大量行
对于每一行,我有3列我关心
典型的行如下所示:
AccountNumber | basecode | subcode
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9689787209368901 | AQTXG AQTXG AQTXG AQTXG ACC5Z | ZQ596 ZQ596 ZQ596 ZQ655 ZC655
某些基本代码需要与相应的子代码一起删除。 basecode和supcode都是由空格分隔的有序列表。我需要一个查询,我输入基本代码,它删除基本代码和子代码,并保持列表的其余部分完整。
每行具有相同数量的基码和子码项。代码数量可以在0到45之间变化。相同的基本代码可以多次出现。所有字段都是varchars。
这样数据最终(动态解析)如下:(因为每个acct有一个可变数量的基本码/子码(对)。
如果我想删除“ACC5Z”,那么我应该
AccountNumber | basecode | subcode
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9689787209368901 | AQTXG AQTXG AQTXG AQTXG | ZQ596 ZQ596 ZQ596 ZQ655
如果我想删除“AQTXG”,那么我应该
AccountNumber | basecode | subcode
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9689787209368901 | ACC5Z | ZC655
答案 0 :(得分:1)
试试这个
DECLARE @t TABLE (AccountNumber VARCHAR(100),Basecode VARCHAR(100),Subcode VARCHAR(100))
INSERT INTO @t SELECT 9689787209368901,'AQTXG AQTXG AQTXG AQTXG ACC5Z','ZQ596 ZQ596 ZQ596 ZQ655 ZC655'
DECLARE @BaseCodetoRemove VARCHAR(10) = 'AQTXG'
;WITH CTE AS(
SELECT
AccountNumber
,LTRIM(RTRIM(SUBSTRING(Basecode, Number ,CHARINDEX(' ', Basecode + ' ', Number ) - Number))) AS Basecode
, LTRIM(RTRIM(SUBSTRING(Subcode, Number ,CHARINDEX(' ', Subcode + ' ', Number ) - Number))) AS Subcode
FROM @t
JOIN master..spt_values ON Number <= DATALENGTH(Basecode) + 1 AND type='P'
AND SUBSTRING(' ' + Basecode, Number , 1) = ' ')
,CTE2 AS(
SELECT *
FROM CTE
WHERE BaseCode <> @BaseCodetoRemove)
SELECT AccountNumber
,STUFF((SELECT ' ' + CAST(Basecode AS vARCHAR(MAX))
FROM CTE2 t2 WHERE t1.AccountNumber = t2.AccountNumber
FOR XML PATH('')),1,1,'')Basecode
,STUFF((SELECT ' ' + CAST(Subcode AS vARCHAR(MAX))
FROM CTE2 t2 WHERE t1.AccountNumber = t2.AccountNumber
FOR XML PATH('')),1,1,'')Subcode
FROM CTE2 t1
GROUP BY t1.AccountNumber