Row count of a stored procedure from another stored procedure

∥☆過路亽.° 提交于 2020-01-03 13:34:08

问题


I have various stored procedures. I need a stored procedure to execute a stored procedure and then return only the row count (number of returned rows by the called procedure) and I need to receive it in c# code.

What's the best way to do this?

Situation: I have various stored procedures which is called from c# code. Now for another purpose i need to know the number of rows returned by a procedure (I don't want the returned rows, I just the need the number of rows). I cannot change the stored procedure itself as many of my c# code is using them, so things may break if I change the procedures. That's why I am locking for a procedure which will take input and execute a procedure (dynamically) and return the number of rows but not the result or rows.

I could take stored procedure string and execute it like

EXEC ('StoredProcedure @Keyword = ''' + @Key + '''')

I have Id as a column in each possible returned row. I could store the ids and count it but I don't know what if that's the best idea.

My database is pretty big. I could use executenonquery() in c# but it's returning -1 when I execute any stored procedure with it. What's the best way. Thank you.


回答1:


Assuming you are using SQL Server (which is possible from the code snippets), perhaps something like this would work for you:

exec('exec <your stored procedure goes here>; select @@RowCount')

Since you are running SQL Server, I can think of one solution that is not necessarily pretty.

Create a temporary table (table variable if you have a more recent version of SQL Server). Then execute:

exec(`
declare @t table (
   <columns go here>
);

insert into @t
    exec(''<your exec here>'');

select @rowcount
');

And now that I've said that, I would recommend sp_executesql. This goes something like this:

declare @sql nvarchar(max) = N'exec '+@YOURQUERY + '; set @RowCount = @@RowCount';

exec sp_executesql @sql, N'@RowCount int output', @RowCount = RowCount output;

I spent most of yesterday debugging an arcane condition that arises when you call a stored procedure inside an insert.




回答2:


You can try this in your child stored procedure :

CREATE PROC PawanXX
(
 @a INT
,@b INT OUTPUT
)
AS
BEGIN

SELECT TOP 2 * FROM X

SET @b = @@ROWCOUNT

RETURN @b

END
GO

The main stored procedure where we call all other sps

 DECLARE @RC int
 DECLARE @a int
 DECLARE @b int

EXECUTE @RC = [dbo].[PawanXX] 
   @a
  ,@b OUTPUT

SELECT @RC

The output for the same ProcessName Parent Child


ShareDrafts Job12 Job03 ShareDrafts Job13 Job58

(2 row(s) affected)


2

(1 row(s) affected)



来源:https://stackoverflow.com/questions/14735025/row-count-of-a-stored-procedure-from-another-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!