December 7, 2006 at 4:10 am
Hello,
I need to create a storred procedure that contains an if statement that contains a execute of and procedure if the "if" statement is true.
I have to do a select statement and set the value of an counter with the amount of row returned if infact the select finds a match in the database. How do I go about setting up and populating such an counter?
Thanks
Olivia
December 7, 2006 at 6:21 am
I am going to assume that the first and second questions are related:
create proc myproc @key int
as
-- Second question (count)
declare @numRec int
select @numRec = count(*) from MyTable
where myKey = @key
-- First question: if
if @numRec > 0
begin
print 'do something since records found'
end
else
begin
print 'do something else since no records found'
end
Russel Loski, MCSE Business Intelligence, Data Platform
December 7, 2006 at 7:20 am
Thanks,
This is exactly what I had in mind.
Cheers
Olivia
December 8, 2006 at 7:45 am
If you are doing the count only to check if a record matching your criteria exists, you are better off using EXISTS.. Do the exact same thing as suggested above, except instead of saying:
declare @numRec int
select @numRec = count(*) from myTable
where myKey = @key
if @numRec > 0 .......
try this:
IF EXISTS (SELECT * FROM MyTable WHERE myKey = @key)
BEGIN
PRINT 'Do something since records found'
END
ELSE
BEGIN
PRINT 'Do something else since no records found'
END
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply