简体   繁体   English

SQL Server存储过程存储返回值

[英]SQL Server Stored Procedure store return value

Helo, 直升机,

My question is I have one Stored Procedure in SQL Server that returns counts of a field. 我的问题是我在SQL Server中有一个存储过程,它返回一个字段的计数。 I want to store the results of this Stored Procedure in a variable (scalar?) of a different stored procedure. 我想将此存储过程的结果存储在不同存储过程的变量(标量?)中。

sp_My_Other_SP:

CREATE PROCEDURE [dbo].sp_My_Other_SP
@variable int OUTPUT -- The returned count
AS

BEGIN -- SP

SET NOCOUNT ON;

SET @SQL = "SELECT COUNT(*) FROM blah"
EXEC(@SQL)

END -- SP

I currently do it like: 我目前这样做:

DECLARE @count int

EXEC sp_My_Other_SP @count OUTPUT

Then I use it like 然后我就像使用它一样

IF (@count > 0)
BEGIN
...
END

However its returning the other Stored Procedure results as well as the main Stored Procedure results which is a problem in my .NET application. 然而,它返回其他存储过程结果以及主要存储过程结果,这是我的.NET应用程序中的问题。

-----------
NoColName
-----------
14

-----------
MyCol
-----------
abc
cde
efg

(Above is an attempted representation of the results sets returned) (上面是对返回的结果集的尝试表示)

I would like to know if there is a way to store the results of a Stored Procedure into a variable that doesn't also output it. 我想知道是否有办法将存储过程的结果存储到一个不输出它的变量中。

Thanks for any help. 谢谢你的帮助。

You can capture the results of the stored procedure into a temp table so it is not returned by the calling stored procedure. 您可以将存储过程的结果捕获到临时表中,以便调用存储过程不会返回它。

create table #temp (id int, val varchar(100))
insert into #temp
exec sp_My_Other_SP @value, @value, @value, @count OUTPUT

Well, the easiest way to fix this is to recode the stored proc so that the select statement that returns the 'other' result set you don't want in this case is conditionally extecuted, only when you are NOT asking for the count 好吧,解决这个问题的最简单方法是重新编码存储过程,以便在这种情况下返回你不想要的“其他”结果集的select语句有条件地被扩展,只有当你不要求计数时

Add another parameter called @GetCount 添加另一个名为@GetCount的参数

@GetCount TinyInt Defualt = 0 // or
@GetCount Bit Default = 0 

Then instead of just 然后而不仅仅是

Select ...

write

   If @GetCount = 1
     Select ...

Have you tried changing 你试过改变吗?

SET @SQL = "SELECT COUNT(*) FROM blah" 
EXEC(@SQL) 

to

SELECT @variable = COUNT(*) FROM blah" 
-- don't do EXEC(@SQL) 

?

THE FIRST PROCEDURE:
CREATE PROC DD43
@ID INT OUTPUT AS
(SELECT @ID=COUNT(*) FROM CS2)

SECOND PROCEDURE:

 CREATE PROC DD45 AS
 DECLARE @COUNT INT
 DECLARE @COUN INT
 EXEC DD43 @COUN OUT --CALLING THE FIRST PROCEDURE
 SET @COUNT= (SELECT @COUN)
 SELECT @COUNT

 EXEC DD45 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM