T-SQL check empty recordset
In many situations when writing procedures in T-SQL for Micrososft SQL server, we set a variable as a result of a query and then before using that variable (specially for numeric results) want to check if that query returned any results at all. This is how we can do it
CREATE PROCEDURE [dbo].[GetClientOpeningBalance]
(
@client_id bigint,
@transdate datetime
)
AS
SET NOCOUNT OFF;
DECLARE @balance_c AS float
DECLARE @balance_t AS float
DECLARE @opening_balance AS float
set @balance_c=(
select top 1 balance_after
from client_transact
where client_id=@client_id
and transdate<@transdate
order by transdate desc, id desc
)
set @balance_t=(
select top 1 client_bal_aft
from trades
where client_id=@client_id
and transdate<@transdate
order by transdate desc, id desc
)
if (COUNT(@balance_t)=0)
set @balance_t=0
if (COUNT(@balance_c)=0)
set @balance_c=0
set @opening_balance=@balance_c+@balance_t
select @opening_balance as Opening_Balance
GO
Comments