Wednesday, March 7, 2012

how if esle statement works?

hi, everybody!

I have some problems with understanding howif esle statment in sql works. I'm trying to write my owncount()-function and its not working withif else :(( I've already implemented it withcase:
select sum(case (hiredate) when (null) then 0 else 1 end) as 'Count' from emp

It's working perfect. Now I want to have the same but usingif else:
select sum(
if( hiredate is null)
begin 0 end
else 1)
as 'Count' from emp

the error message is:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'if'.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '0'.

What is wrong here?

Artur:

If / else does not work within the context of a select list like this; you need to implement as your first select statement with case statement or use a where condition such as something like:

select count(*)
from emp
where hiredate is not null

|||I think you are right, its not possible to use if/esle within select statement.
Thanks!!!
|||In SQL Server, IF - Else is a control flow statement that allows you to conditionaly run blocks of T-SQL code. Case is an expression that can be used inside some statements. SQL Server does not have a CASE Statement like some other languages.|||Artur,

You can have an 'if/then/else' statement within your code, it's just that you have to put 'case when' instead of 'if'. It works exactly the same way.

Try:

select sum(case when hiredate is null then 0 else 1 end) as 'Count'
from emp

Rob

No comments:

Post a Comment