Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL convert column by different condition in select statement

I have a table that contains a string address. I want to select the column text in specific format. However, the column contains different format and it requires different rules. For example,if the column contain words like ‘SHOP’, it will select the wording start with ‘SHOP’.
If the column contains words like ‘BOX’, it will select the wording after ‘BOX’.

tableA 

__________________________
|columna |address        |
__________________________
|a1234   |ddsa SHOP LG123|
__________________________
|4322    |SADA BOX 12-42 |
__________________________
|4632    |123123 ADV  2313|
__________________________

I want something like this.
Select by different condition in different rules in same column.

  SELECT 
    ta.columna,
    if CHARINDEX('SHOP',ta.address) > 0
        RIGHT(ta.address, len(ta.address) - charindex('SHOP', ta.address)+1) AS unit_addr,
    if CHARINDEX('BOX',ta.address) > 0
        RIGHT(ta.address, len(ta.address) - charindex('BOX', ta.address)-8) AS unit_addr,
    if CHARINDEX('ADV',ta.address) > 0
        RIGHT(ta.address, charindex('ADV', ta.address)-3) AS unit_addr
    FROM 
    tableA ta

So the final table will be this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

tableA 

__________________________
|columna |address        |
__________________________
|a1234   |SHOP LG123     |
__________________________
|4322    |12-42          |
__________________________
|4632    |2313           |
__________________________

>Solution :

You need to use a Case expression. Assuming the logic above does what you need, this sort of thing should provide the result in the structure you want…

select ta.columna,
       case 
           when CHARINDEX('SHOP',ta.address) > 0 then
               RIGHT(ta.address, len(ta.address) - charindex('SHOP', ta.address)+1)
           when CHARINDEX('LIGHTBOX',ta.address) > 0 then
               RIGHT(ta.address, len(ta.address) - charindex('LIGHTBOX', ta.address)-8)
           when CHARINDEX('ADV',ta.address) > 0 then
               RIGHT(ta.address, charindex('ADV', ta.address)-3)
       end as address
from tablea ta
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading