sayhaha
sayhaha

Reputation: 789

Loop queried result

I'm totally new to asp. Sorry, if it's really basic but I couldn't find through my research.

I want to query Table_A by ID and NAME. (ID is PK, Name is optional) then if ID is found but Name is null, I want to use that ID to query from other table.

Select * 
From Table_A;

gives me

ID    NAME
1     PAUL
2     BOB
3     NULL

Then save it into somewhere like Cursor in Stored Procedure. Then during the loop, ID has empty name so run Select * From Table_B where ID = 3;

If I tag something, please help out to tag correctly.

Upvotes: 0

Views: 104

Answers (1)

Icarus
Icarus

Reputation: 63966

You don't need to do 2 queries; you can instead do this:

select coalesce(a.name,b.name) as name
      , a.id 
from table_a a left join table_b b on b.id=a.id;

This will return the name from table a if not null; otherwise from table b.

Upvotes: 1

Related Questions