James A Mohler
James A Mohler

Reputation: 11120

Removing parts of field that is space delimited internally

I have a large number of rows in an SQL Server 2008 db

For each row I have 3 columns that I care about

A typical row looks like this:

AccountNumber    | basecode                      | subcode
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9689787209368901 | AQTXG AQTXG AQTXG AQTXG ACC5Z | ZQ596 ZQ596 ZQ596 ZQ655 ZC655

Certain basecodes need to be removed along with their corresponding sub codes. Both basecode and supcode are ordered lists delimited by spaces. I need a query that I input the base code and it deletes the basecode and subcode and leaves the rest of the the list intact.

Each row has the the same number of basecode and subcode items. The number of codes can vary from 0 to 45. The same basecode can appear multiple times. All fields are varchars.

So that the data ultimately (dynamically parses) out as so: (because there is a variable number of basecodes/subcode (pairs) per acct.

If I am trying to remove "ACC5Z" then I should have

AccountNumber    | basecode                | subcode
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9689787209368901 | AQTXG AQTXG AQTXG AQTXG | ZQ596 ZQ596 ZQ596 ZQ655

If I am trying to remove "AQTXG" then I should have

AccountNumber    | basecode   | subcode
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9689787209368901 | ACC5Z      | ZC655

Upvotes: 1

Views: 125

Answers (1)

Niladri Biswas
Niladri Biswas

Reputation: 4171

Try this

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

Upvotes: 1

Related Questions