Helpex - Trao đổi & giúp đỡ Đăng nhập
9

Helo,

My question is I have one Stored Procedure in SQL Server that returns counts of a field. 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.

-----------
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.

9 hữu ích 3 bình luận 48k xem chia sẻ
13

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
13 hữu ích 3 bình luận chia sẻ
4

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

Add another parameter called @GetCount

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

Then instead of just

Select ...

write

   If @GetCount = 1
     Select ...
4 hữu ích 0 bình luận chia sẻ
2

Have you tried changing

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

to

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

?

2 hữu ích 0 bình luận chia sẻ
0
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 
0 hữu ích 1 bình luận chia sẻ
loading
Không tìm thấy câu trả lời bạn tìm kiếm? Duyệt qua các câu hỏi được gắn thẻ sql sql server sql-server-2005 sql server 2008 stored-procedures , hoặc hỏi câu hỏi của bạn.

Có thể bạn quan tâm

loading