Sample Header Ad - 728x90

How to optimize multiple WHEN that are using differents static string?

0 votes
2 answers
48 views
I have a table like that: | Id | Note | Client | | -- | ------------------------------------------------------ | ------- | | 1 | Long note that have
multiple lines
Client: Name | null | | 2 | Anoter note that have multiple lines
Customer: Name | null | | 3 | Third note that have multiple lines
Client : Name
line | null | | 4 | Line: A
Client : Name
line | null | | 5 | Line B
B : Line
Customer : Name
line
others | null | I want to extract client informations from the "Note" column, to put it on the "Client" column with only one SQL query. I gave some example that represent the real thousand of line I have. I firstly made this query:
SELECT
    CASE
        WHEN posclient != 0 THEN SUBSTRING(
            Note,
            posclient + LENGTH('Client: '),
            LOCATE('\n', Note, posclient + LENGTH('Client: ')) - (posclient + LENGTH('Client: '))
        )
        WHEN poscustomer != 0 THEN SUBSTRING(
            Note,
            poscustomer + LENGTH('Customer : '),
            LOCATE('\n', Note, poscustomer + LENGTH('Customer : ')) - (poscustomer + LENGTH('Customer : '))
        )
        WHEN poscontact != 0 THEN SUBSTRING(
            Note,
            poscontact + LENGTH('Contact : '),
            LOCATE('\n', Note, poscontact + LENGTH('Contact : ')) - (poscontact + LENGTH('Contact : '))
        )
        ELSE ''
    END AS client,
    Id
FROM (SELECT Id, Note,
        LOCATE('Customer : ', Note) as poscustomer,
        LOCATE('Client: ', Note) as posclient,
        LOCATE('Contact : ', Note) as poscontact
    FROM myTable) x 
WHERE (poscustomer != 0 OR posclient != 0 OR poscontact != 0)
As there is duplicated code (the WHEN part), it's hard to read and not very fine if I have another way to add. And I have: there is at least 6 ways to write the client. I want to optimize this part:
WHEN poscontact != 0 THEN SUBSTRING(
   Note,
   poscontact + LENGTH('Contact : '),
   LOCATE('\n', Note, poscontact + LENGTH('Contact : ')) - (poscontact + LENGTH('Contact : '))
)
To be "generic" but I don't know how as I'm not in programming language. In php, that would be easy, but I can't use programming language, I have to use only one query. One thing that can be very helpful: the is only ONE way to write the client for each line. It will always contains only one. How can I do?
Asked by Elikill58 (181 rep)
Aug 28, 2024, 12:08 PM
Last activity: Aug 28, 2024, 01:40 PM