Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello,

I have a table e.g. student like this:-
roll    mark
--------------
1       50
2       60
3       70
--------------


when I making query
SQL
select mark from student where roll=1


It is showing
mark
-----
50


but when I am writing
SQL
select mark from student where roll=4


It is showing
mark
-----


But I want if the condition is not satisfied then it return zero means like:-
mark
----
0



Thanks.
Posted
Updated 3-Feb-12 18:25pm
v3

That is not a nice thing to do - it means you cannot tell the difference between a student that doesn't exist, and a student that scores zero. However:
SQL
IF EXISTS (SELECT mark FROM student WHERE roll=4)
SELECT mark FROM student WHERE roll=4
ELSE
SELECT 0
But you should find a better way to organise your code instead. If nothing else, this is very inefficient!
 
Share this answer
 
Comments
That's Aragon 3-Feb-12 7:38am    
Agreed with OriginalGriff. 5!. Application should have some differentiation mechanism for students who have mark 0 and whose record is not available in table like here for roll=4 is not available then it should return mark=-1 Later on, you can display proper message for mark=-1 and mark=0 records.
SQL
select isnull((select mark  from @temptable where id=4),0) as mark


This query is based on SQL 2008 Data Base.@temptable is table name.
 
Share this answer
 
v3
Comments
Rajeev Jayaram 3-Feb-12 6:34am    
5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900