Click here to Skip to main content
15,901,284 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
If one record in Table A is null (ex. name) then select that record from Table B.

Case statement for if record from table A is null e.g name column appear blank some value so i can select those from another table require Case Statement in sql for select query
Posted
Comments
Sebastian T Xavier 12-Jul-12 6:32am    
what have you tried? Can you post your code?

1 solution

SQL
DECLARE @A TABLE (ID INT IDENTITY(1,1),NAME VARCHAR(20))
DECLARE @B TABLE (ID INT IDENTITY(1,1),NAME VARCHAR(20))

INSERT INTO @A VALUES('A TEJAS')
INSERT INTO @A VALUES('A JAYESH')
INSERT INTO @A VALUES(null)

INSERT INTO @B VALUES('B TEJAS')
INSERT INTO @B VALUES('B JAYESH')
INSERT INTO @B VALUES('B KRUNAL')

SELECT * FROM @A

SELECT CASE WHEN A.NAME IS NULL THEN B.NAME ELSE A.NAME END AS NAME FROM @A AS A
INNER JOIN @B AS B ON A.ID = B.ID


--Out Put like this..

--simple select query output

ID          NAME
----------- --------------------
1           A TEJAS
2           A JAYESH
3           NULL


--case when select query output

NAME
--------------------
A TEJAS
A JAYESH
B KRUNAL


the other way is like this

SQL
SELECT ISNULL(A.NAME,B.NAME)

suggested by barneyman
 
Share this answer
 
v2
Comments
barneyman 12-Jul-12 7:12am    
isn't SELECT ISNULL(A.NAME,B.NAME) ... more effective?
Tejas Vaishnav 12-Jul-12 7:25am    
asking for case when that's why i post the answer with case when, i already know ISNULL function, and you are right it's more effective.

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