views:

63

answers:

3

I'm trying to alter the results of a Transact-SQL (MS SQL Server) report that is currently showing:

CompanyA     DVCE3
CompanyB     DVCE2
CompanyC     DVCE3
CompanyD     NULL 
CompanyE     DVCE3

and I would like it instead to show:

CompanyA     36
CompanyB     24
CompanyC     36
CompanyD      
CompanyE     36

I'm sure the answer to this is to use some kind of if/else statement or a case statement, but I'm not sure of the syntax of this in T-SQL or where it should go in my query.

My basic query looks like this:

SELECT
   companyName
   , term
FROM tableA a
   JOIN tableB b on a.id = b.id ...
WHERE 
   customerNumber IS NOT NULL
   AND companyName != 'TEST'... ;

Thanks for your help.

+4  A: 

If you only have a few replacements you could stick them in a case statement as below.

SELECT
   companyName
   ,CASE term WHEN  'DVCE3' THEN '36' WHEN 'DVCE2' THEN '24' ELSE '' END AS term
FROM tableA a
   JOIN tableB b on a.id = b.id ...
WHERE 
   customerNumber IS NOT NULL
   AND companyName != 'TEST'... ;

If you have more or you will be repeating this logic in other queries you could maybe set up a mapping table (either a permanent table, view, or an inline TVF) that you can then join onto.

Martin Smith
Minor detail: you also need to handle the case for converting NULL to ''.
Joe Stefanelli
@Joe - Ooh I hadn't noticed that. Will fix now thanks.
Martin Smith
+5  A: 

Replace your "term" field with the following:

CASE WHEN term='DVCE3' THEN '36' WHEN term='DVCE2' THEN '24' ELSE '' END as term

I'll rewrite it for readability:

CASE
    WHEN term='DVCE3' THEN '36'
    WHEN term='DVCE2' THEN '24'
    ELSE ''
END as term
Joe Philllips
+1 For handling the `ELSE` case I hadn't noticed that.
Martin Smith
Excellent thanks, this works. The only slight side-effect is that, for some reason, wherever the original was returning NULL, your result is returning the number 0.
dvanaria
@dvanaria - SQL converts '' to 0 for some bizarre reason when casting as numeric. Put all the numbers in single quotes e.g. `'36'` so it treats that column as a string.
Martin Smith
This gave me the exact output I was looking for (by putting the 24 and 36 in quotes). Thanks for the help!
dvanaria
+1  A: 

A Case statement will work. However a better answer might be to place that data into a table and do a join or just place it into a field in your company table. This makes it MUCH more extensible in the long run.

CREATE TABLE CompanyTerms (
    id INT,
    CompanyName NVARCHAR(100) NOT NULL, 
    Term NVARCHAR(100) NULL
)

...

SELECT
   companyName
   , c.Term
FROM tableA a
   JOIN tableB b on a.id = b.id ...
   JOIN CompanyTerm c ON c.id = a.id
WHERE 
   customerNumber IS NOT NULL
   AND companyName != 'TEST'... ;
Brian Duncan
This sounds like a good suggestion, but for the scope of this report I don't have to worry too much about extensibility, at least not regarding what values could fall in this column in the result.
dvanaria