Link to home
Start Free TrialLog in
Avatar of tommym121
tommym121Flag 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?
Avatar of lcohan
lcohan
Flag of Canada image

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
Avatar of lcohan
lcohan
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of tommym121

ASKER

Thanks