Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Case statement and conversion failed

Author  Topic 

michaelb
Yak Posting Veteran

69 Posts

Posted - 2009-02-09 : 19:21:16
Hi,

I have the following case statement in a query, but when I run it, it returns 'Conversion failed when converting the varchar value 'D' to data type int.


case when t1.groupcode in (100,110,111,113,114,115,126) then 'A'
when t1.groupcode in (112,116,125,129,130,144) then 'B'
when t1.groupcode in (117,118,119,120,121,122,123,124,141) then 'C'
when t1.groupcode in (127,131,132,133,134,135,136,137,140,142,143) then 'D'
else 0 end as 'Group'



I'm guessing this is because the words are varchar, but the numbers are int. Do I need to cast the numbers as varchar? If so, how do I do this within a case statement?

Thanks in advance.

Kind Regards,
Michael

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2009-02-09 : 19:27:00
[code]case when t1.groupcode in (100,110,111,113,114,115,126) then 'A'
when t1.groupcode in (112,116,125,129,130,144) then 'B'
when t1.groupcode in (117,118,119,120,121,122,123,124,141) then 'C'
when t1.groupcode in (127,131,132,133,134,135,136,137,140,142,143) then 'D'
else NULL end as 'Group'[/code]
Go to Top of Page

michaelb
Yak Posting Veteran

69 Posts

Posted - 2009-02-09 : 19:38:08
Excellent. Thankyou heaps!
Go to Top of Page

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2009-02-09 : 19:42:36
If you need 0 you can do like this:

case when t1.groupcode in (100,110,111,113,114,115,126) then 'A'
when t1.groupcode in (112,116,125,129,130,144) then 'B'
when t1.groupcode in (117,118,119,120,121,122,123,124,141) then 'C'
when t1.groupcode in (127,131,132,133,134,135,136,137,140,142,143) then 'D'
else '0' end as 'Group'
Go to Top of Page
   

- Advertisement -