Question

I am trying to do some text formatting with sql (MS SQL server 2008). I have three variables which are either going to return empty strings or some sort of text, they will never be null. I would like the display the text in the following way:
@Var1='A' @Var2='B' @Var3='C' ==> A, B, C
@Var1='A' @Var2='' @Var3='C' ==> A, C
@Var1='' @Var2='B' @Var3='C' ==> B, C
@Var1='' @Var2='' @Var3='C' ==> C
.
.
.
@Var1='' @Var2='' @Var3='' ==>
etc

Here is a simplified version of what I have...

DECLARE @Var1 NVARCHAR(100)
DECLARE @Var2 NVARCHAR(100)
DECLARE @Var3 NVARCHAR(100)
SET @Var1 = 'A'
SET @Var2 = 'B'
SET @Var3 = 'C'
SELECT 
ISNULL(NULLIF(@Var1,''), '') 
    + 
        CASE
            WHEN NULLIF(@Var1,'') IS NOT NULL AND NULLIF(@Var2,'') IS NOT NULL THEN ', ' ELSE '' 
        END 
    +
ISNULL(NULLIF(@Var2,''),'')
    +
        CASE
            WHEN NULLIF(@Var2,'') IS NOT NULL AND NULLIF(@Var3,'') IS NOT NULL THEN ', ' ELSE '' 
        END 
    +
ISNULL(NULLIF(@Var3,''),'')

I feel like I am missing some important details. Let me know if there is any clarification needed.

Was it helpful?

Solution

Try:

select  case 
        when str is null then ''
        else left(str, len(str)-1) -- Remove last comma
        end
from    (
        select  case when len(@Var1) > 0 then @Var1 + ', ' else '' end + 
                case when len(@Var2) > 0 then @Var2 + ', ' else '' end + 
                case when len(@Var3) > 0 then @Var3 + ', ' else '' end as str
        ) as SubQueryAlias

Or with a reverse trick to avoid the subquery:

select  reverse(stuff(reverse(
        case when len(@Var1) > 0 then @Var1 + ', ' else '' end +
        case when len(@Var2) > 0 then @Var2 + ', ' else '' end +
        case when len(@Var3) > 0 then @Var3 + ', ' else '' end
        ), 1, 2, ''));

The key point here is that SQL Server is not very good at text formatting :) You're infinitely better off in a client side language like C#.

Live example at SQL Fiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top