Wednesday, March 28, 2012

IF ELSE in a select statement

Hello friends
Is there any possible to use a if.. else in a select statement?
for example
select ,field_a
,field_b
, if field_a like 'TEST' then field_c else field_d
from table_abc
I know that this is not working but I need somethink like this...
Can anyone help me please?You have to use a "case expression". You can not use flow control as part of
the select statement.
select ,field_a
,field_b
, case when field_a = 'TEST' then field_c else field_d end as c1
from table_abc
AMB
"Bruno" wrote:

> Hello friends
> Is there any possible to use a if.. else in a select statement?
> for example
> select ,field_a
> ,field_b
> , if field_a like 'TEST' then field_c else field_d
> from table_abc
> I know that this is not working but I need somethink like this...
> Can anyone help me please?
>|||You need a CASE expression...
select ,field_a
,field_b
, CASE
WHEN field_a like 'TEST' then field_c
ELSE field_d
END AS testField
from table_abc
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
--
"Bruno" <Bruno@.discussions.microsoft.com> wrote in message
news:489487A4-D2AB-4DEE-87D7-7A5B52F2A821@.microsoft.com...
> Hello friends
> Is there any possible to use a if.. else in a select statement?
> for example
> select ,field_a
> ,field_b
> , if field_a like 'TEST' then field_c else field_d
> from table_abc
> I know that this is not working but I need somethink like this...
> Can anyone help me please?
>|||What you want is CASE. Check out CASE in BooksOnLine for details.
Andrew J. Kelly SQL MVP
"Bruno" <Bruno@.discussions.microsoft.com> wrote in message
news:489487A4-D2AB-4DEE-87D7-7A5B52F2A821@.microsoft.com...
> Hello friends
> Is there any possible to use a if.. else in a select statement?
> for example
> select ,field_a
> ,field_b
> , if field_a like 'TEST' then field_c else field_d
> from table_abc
> I know that this is not working but I need somethink like this...
> Can anyone help me please?
>|||hi
you can use CASE statement instead
best Regards,
Chandra
http://chanduas.blogspot.com/
http://www.SQLResource.com/
---
"Bruno" wrote:

> Hello friends
> Is there any possible to use a if.. else in a select statement?
> for example
> select ,field_a
> ,field_b
> , if field_a like 'TEST' then field_c else field_d
> from table_abc
> I know that this is not working but I need somethink like this...
> Can anyone help me please?
>|||Thanks to everyone
I appreciate a lot
"Andrew J. Kelly" wrote:

> What you want is CASE. Check out CASE in BooksOnLine for details.
> --
> Andrew J. Kelly SQL MVP
>
> "Bruno" <Bruno@.discussions.microsoft.com> wrote in message
> news:489487A4-D2AB-4DEE-87D7-7A5B52F2A821@.microsoft.com...
>
>

No comments:

Post a Comment