How to get row count of select statement inside stored procedure in SQL Server - sql

I have requirement where I want get row count of select statement inside stored procedure and if row count is equal to 0 then only it will execute the next statement
select A, B, C
from AT
where B = 1
If the above statement returns any rows, then it will not execute further but if this statement do not have any row then it will execute next statement. I have tried it using in two ways
##rowcount - it's not working properly
Using temp table by inserting select statement into table getting row count of table but using temp table is not optimize way
Is there any solution?

You could use IF NOT EXISTS:
IF NOT EXISTS (select A,B,C from AT where B=1)
BEGIN
-- sth
END
is there any solution like getting into variable without hitting to database again and again
DECLARE #my_rowcount INT;
select A,B,C from AT where B=1;
SET #my_rowcount = ##ROWCOUNT; -- immediately after select get ##ROWCOUNT
...
IF #my_rowcount = 0
BEGIN
-- sth
END
EDIT:
##ROWCOUNT Globle variable for database so it may return wrong Value if any other select statement processed in other sp in same databe
Nope. ##ROWCOUNT:
Returns the number of rows affected by the last statement.
You could easily check it with your SSMS(open 2 tabs, select 1 and 2 rows on each of them and then get ##ROWCOUNT respectively).

Related

Stored procedure has multiple SELECT statements

This stored procedure has multiple SELECT statements - I need to write a condition based on one SELECT statement results among them without altering the stored procedure:
CREATE PROC Test
AS
BEGIN
SELECT 1 AS ID
FROM EMPLOYEE
SELECT NAME, ADDRESS, STATE
FROM EMPLOYEE --NEED TO TAKE ROW COUNT
END
After executing the stored procedure, I'll get 2 result sets. But I need to row count of 2nd select statement, without altering the stored procedure.
Based on that rowcount, I need to work further.
exec Test
select ##rowcount
In this case, ##rowcount will always return last result set row count.

Stored Procedure

I am using SQl-server 2012 and this code is inside in a Stored Procedure.
These are my SQL queries.I want to execute "Insert" query when "Update" query not executed.
If Update query executed,then insert query should not be executed.
Update tblStock Set Balance= Balance + #ReduceRawQty
Where LocCode=#LocCode
AND ItemCode=#rawitemcode
and CostPrice=#rawcostprice
Insert Into tblStock(LocCode, ItemCode, CostPrice, Balance,Transfer,PCode)
Values(#LocCode,#rawitemcode,#RawCostPrice,#RawQty,0,#PCode)
Is there any method to do this ,please help me
You can check ##ROWCOUNT to see how many rows were affected by the UPDATE statement:
UPDATE ...
IF ##ROWCOUNT = 0
INSERT ...
Alternatively you can use EXISTS to check for a row first and decide which operation to perform:
IF EXISTS (SELECT 1 FROM tblStock WHERE LocCode=#LocCode AND ItemCode=#rawitemcode and CostPrice=#rawcostprice)
UPDATE ...
ELSE
INSERT ...

getting number of records updated or inserted in sql server stored procedure

I have an SP that inserts some records and updates others and deletes some. What I want is to return the count values of what was inserted and what was updated and what was deleted. I thought I could use ##ROWCOUNT but that is always giving me a 1.
After my INSERT I run:
PRINT ##ROWCOUNT
But my message console shows what really happened and this number:
(36 row(s) affected)
1
So I can see that 36 records were actually updated but ##ROWCOUNT returned a 1.
I am trying to do the same thing after the UPDATE and DELETE parts of the SP runs with the same result.
##ROWCOUNT will show the number of rows affected by the most recent statement - if you have any statements between the INSERT and the PRINT then it will give you the wrong number.
Can you show us a little more code so we can see the order of execution?
Depending on how #ninesided's answer works for you, you could also use the output clause on each update/insert/delete and get the counts from there.
Example:
declare #count table
(
id int
)
update mytable
set oldVal = newVal
output inserted.field1 into #count
select count(*) from #count
You could reuse the count table throughout, and set variables as needed to hold the values.

Whats Select '1' for in the following stored proceedure

BEGIN
IF EXISTS(SELECT * FROM Table1 WHERE ID=#ID)
BEGIN
UPDATE Table1 SET Name=#Name WHERE ID=#ID
SELECT '1'
END
ELSE
SELECT '0'
END
Is this the row no. of the table or what ?
Also "IF EXISTS" is checking what ? the table or if the ID exists or not ??
It looks like whoever wrote that Stored Procedure is using that as a return value to indicate success or failure.
Doing things that way will result in a single row with a single column being returned for each call to the procedure.
The correct way to handle this would be to actually use the return value of the stored procedure, rather than returning the single column single row:
BEGIN
IF EXISTS(SELECT * FORM Table1 WHERE ID = #ID)
BEGIN
UPDATE Table1 SET Name = #Name WHERE ID = #ID
RETURN 1
END
RETURN 0
END
The IF EXISTS is checking if there is a row in Table1 with the given ID. If there is a row it will update that row with the given name. The Select "1" will return "1" and Select "0" returns "0". The "1" or "0" would indicate if the row was found or not.
Presumably some calling code checks this value to determine if a row was updated or not.
Rather than checking and updating (two table accesses) you might as well do this.
UPDATE Table1 SET Name=#Name WHERE ID=#ID
SELECT CASE WHEN ##Rowcount = 0 THEN 0 ELSE 1 END
If id is the PK then you can just do
UPDATE Table1 SET Name=#Name WHERE ID=#ID
SELECT ##Rowcount
Note as long as SET NOCOUNT is not on then the number of rows affected will get passed back to the client application anyway.
Select '1' is used to indicate that Table1 contains the id value #ID (a parameter) was updated. Select '0' indicates that Table1 does not contain the id value #ID.

SQL - Counting Returned Records

I'm building a stored procedure. This stored procedure needs to insert a record if a record with a specific value does not exist. If the value does exist, I need to update the record. The problem I'm having is determining if a record with the given value exists or not. I am using the following code:
DECLARE #record1ID as char(36)
SET #record1ID = (SELECT TOP 1 ID FROM Person WHERE [Role]='Manager')
DECLARE #record2ID as char(36)
SET #record2ID = (SELECT TOP 1 d.ID FROM Department d WHERE d.[ManagerID]=#record1ID)
-- If #record2ID is set update record, otherwise add record
-- how do I setup this if/else statement?
Thank you!
If this were a SQL Server as it looks like, you could do a count like this:
declare #rec_counter as int
set #rec_counter = 0
select #rec_counter = count(*) FROM Department d WHERE d.[ManagerID]=#record1
if (#rec_counter > 0)
begin
-- do whatever here
end
IF (EXISTS YOUR_SELECT)
BEGIN ...
or
IF (#record2ID IS NULL)
BEGIN ...
or use select count(*) instead of selecting a value