Reputation: 109
Is it possible to check the result of a SELECT statement, and based on whether rows were returned from that query or not, execute another SELECT statement?
I had the following in mind, but it doesn't work.
SELECT IF(
(SELECT * FROM client_emails ce WHERE ce.client_id = 3),
(SELECT * FROM client_emails ce WHERE ce.client_id = 3),
(SELECT * FROM emails)
)
Upvotes: 0
Views: 290
Reputation: 663
you can definitely check for nulls.
Here's a sample code that'll show you how to check for nulls and use it in a conditional block using TSQL
--check for null
SELECT *
FROM dbo.Accounts
WHERE name IS NOT NULL
--check for non-null
SELECT *
FROM dbo.Accounts
WHERE name IS NOT NULL
--checking for null in conditional block
IF(EXISTS(SELECT 1 FROM dbo.Accounts WHERE name IS NULL))
BEGIN
--create new account
INSERT INTO dbo.Account
VALUES('John')
END
----------------- UPDATE TO YOUR COMMMENT ------------------------
based on the 1st code sample, you know that you can check if a row exist or not by using EXISTS. so, if you spent some time thinking about it, you would realize that you can do something like the following
/*
Execute SELECT statement A.
If rows had been returned,
Execute SELECT statement B.
*/
--statement B
SELECT *
FROM dbo.Accounts a
WHERE a.name = 'John'
AND EXISTS
(
--statement A
SELECT 1
FROM dbo.Address
WHERE account_id = a.account_id
)
/*
If rows had not been returned,
Execute SELECT statement C.
*/
--statement c
SELECT *
FROM dbo.Accounts a
WHERE a.name = 'David'
AND NOT EXISTS
(
--statement A
SELECT 1
FROM dbo.Address
WHERE account_id = a.account_id
)
Upvotes: 1