Solved

how to determine the records affected in an update sql statement in a stored procdure?

Posted on 2004-10-08
3
1,301 Views
Last Modified: 2012-06-27
If I have a stored procedure like this:
CREATE PROCEDURE spTest
@UserID int
AS
set NOCOUNT ON
begin

UPDATE pwreset SET UpdateDate = getdate()
             WHERE UserID = @UserID

--get # of records updated (0 or 1)
--and then do something based on that info
--if #recsAffected > 0
--   select 'true' as result
--else
--   select 'false' as result

end
SET NOCOUNT OFF
GO


how would I know how many records were affected?  I guess I could alter the statement a bit and then do some sort of query to find out if the record is found, but if I can just tell if there was a record updated, it'd save a step...

Thanks.
0
Comment
Question by:davexxxx
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 6

Accepted Solution

by:
acampoma earned 75 total points
ID: 12262523
you can set nocount off at the beginningof your statement
or  return @@RowCount
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 12262919
Capture the value of @@ROWCOUNT *immediately after* the UPDATE statement - otherwise the @@ROWCOUNT value gets overwritten by another statement.  For example:

begin

UPDATE pwreset SET UpdateDate = getdate()
             WHERE UserID = @UserID
-- *don't add any statements here!* (or save @@ROWCOUNT in a local var. first)
IF @@ROWCOUNT > 0
   select 'true' as result
else
   select 'false' as result
-- can add statements here if needed

end
SET NOCOUNT OFF
GO

0
 

Author Comment

by:davexxxx
ID: 12278247
perfect...  @@RowCount was what I was looking for.
0

Featured Post

Edgartown IT Case Study

Learn about Edgartown's quest to ensure the safety and security of the entire town's employee and citizen data. Read the case study!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

695 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question