Avatar of tommym121
tommym121
Flag for Canada asked on

SQL - How to concatenate a string with condition

I have a table tbl1

Name | account code | Type  | detail
-----------------------------------------------------------------
P1       | 12345              | Open | detail1
P2       | 12341              | Close |

I would like to do a Select that will selectively concatenate the information into a description if the information is available.
e.g

for first record
P1 - 12345 - Open (detail1)
but for second record, no detail being concatenated since it is not available.
P1 - 12341 - Close


How will I do that?
Microsoft SQL Server

Avatar of undefined
Last Comment
tommym121

8/22/2022 - Mon
lcohan

It would be something like:


select
      case when [type] = 'closed'
                  then (select Name+account+code+[TYPE])
                  else (select Name+account+code+[TYPE]+detail)
             end as col1
from tbl1
ASKER CERTIFIED SOLUTION
lcohan

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
lcohan

Darn..."close" not closed so once again - sorry:


select
      case when [type] = 'close'
                  then (select Name+'-'+cast(account as sysname)+'-'+code+'-'+[TYPE])
                  else (select Name+'-'+cast(account as sysname)+'-'+code+'-'+[TYPE]+'-'+detail)
             end as col1
from tbl1
tommym121

ASKER
Thanks
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck