Skip to content
Advertisement

How can I build a string in SQL with various fields depending on value?

So I have several fields that may be zero or not. The fields are A,B,C,D,E. For my records returned, I want to build a string that has non-zero values. So the records returned might look like this:

A=3, D=2 -- Only A and D are non-zero.
B=2, C=3, D=2 -- B,C,D are non-zero.

Etc.

Easy to build strings like:

A=3, B=0, C=0, D=2, E=0
A=0, B=2, C=3, D=2, E=0

I just don’t want to include the zero value fields in the AS portion.

Advertisement

Answer

If you want to build string from A,B,C,D,E field, then try using CONCAT+CASE: (if it is SQL Server):

   SELECT
   CONCAT (
      CASE WHEN A=0 then '' ELSE CONCAT('A=',A,' ') END, 
      CASE WHEN B=0 then '' ELSE CONCAT('B=',B,' ') END, 
      CASE WHEN C=0 THEN '' ELSE CONCAT('C=',C,' ') END, 
      CASE WHEN D=0 THEN '' ELSE CONCAT('D=',D,' ') END, 
      CASE WHEN E=0 THEN '' ELSE CONCAT('E=',E,' ') END  
           )  FROM Table

For your version try this:

 SELECT
  CASE WHEN A=0 then '' ELSE 'A='+CAST(A AS VARCHAR)+' ' END+ 
  CASE WHEN B=0 then '' ELSE 'B='+CAST(B AS VARCHAR)+' ' END+ 
  CASE WHEN C=0 THEN '' ELSE 'C='+CAST(C AS VARCHAR)+' ' END+ 
  CASE WHEN D=0 THEN '' ELSE 'D='+CAST(D AS VARCHAR)+' 'END+ 
  CASE WHEN E=0 THEN '' ELSE 'E='+CAST(E AS VARCHAR)+' ' END
 FROM Table
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement