sql-server-2008t-sqlvarcharmax

Search text within Varchar(max) column of Sql server


I wanted to write a t-sql query which finds values within a column of a sql server table.

Example,

CREATE TABLE Transactions (Details varchar(max));

Details Column has below type strings stored in it

ID=124|NAME=JohnDoe|DATE=020620121025|ISPRIMARY=True|
TRANSACTION_AMOUNT=124.36|DISCOUNT_AMOUNT=10.00|STATE=GA|
ADDR1=test|ADDR2=test22|OTHER=OtherDetailsHere

ID=6257|NAME=michael|DATE=050320111255|ISPRIMARY=False|
TRANSACTION_AMOUNT=4235.00|DISCOUNT_AMOUNT=33.25|STATE=VA|
ADDR1=test11|ADDR2=test5|OTHER=SomeOtherDetailsHere

Objective is to write query which gives below output

 Name     |   Transaction Amount | Discount
 -------------------------------------------
 JohnDoe  |   124.36             | 10.00
 michael  |   4235.00            | 33.25

Any help would be highly appreciated.

Thanks,

Joe


Solution

  • Why are you storing your data pipe delimited in a single column -- these fields should be added as columns to the table.

    However, if that isn't an option, you'll need to use string manipulation. Here's one option using a couple Common Table Expressions, along with SUBSTRING and CHARINDEX:

    WITH CTE1 AS (
      SELECT 
          SUBSTRING(Details, 
                CHARINDEX('|NAME=', DETAILS) + LEN('|NAME='), 
                LEN(Details)) NAME,
          SUBSTRING(Details, 
                CHARINDEX('|TRANSACTION_AMOUNT=', DETAILS) + LEN('|TRANSACTION_AMOUNT='), 
                LEN(Details)) TRANSACTION_AMOUNT,
          SUBSTRING(Details, 
                CHARINDEX('|DISCOUNT_AMOUNT=', DETAILS) + LEN('|DISCOUNT_AMOUNT='), 
                LEN(Details)) DISCOUNT_AMOUNT
      FROM Transactions
    ), CTE2 AS (
      SELECT 
          SUBSTRING(NAME,1,CHARINDEX('|',NAME)-1) NAME,
          SUBSTRING(TRANSACTION_AMOUNT,1,CHARINDEX('|',TRANSACTION_AMOUNT)-1) TRANSACTION_AMOUNT,
          SUBSTRING(DISCOUNT_AMOUNT,1,CHARINDEX('|',DISCOUNT_AMOUNT)-1) DISCOUNT_AMOUNT
      FROM CTE1
    )
    SELECT * 
    FROM CTE2