Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Stored procedure returning multiple result sets

$
0
0

Hello, 

I have a stored procedure that I've been tasked to add functionality to.  The stored procedure executes a select statement and returns one record, and I need to add failover to it.  

Let's say I have the following:

ALTER PROCEDURE dbo.myTestProc @ObjectCode @Alias @Locale @failoverLocale --Extra value to try if no records exist with the first locale AS

BEGIN

SELECT * from myTable WHERE ObjectCode = @ObjectCode and Alias = @Alias and Locale = @Locale if(@@ROWCOUNT = 0 AND @failoverLocale = '') BEGIN EXEC dbo.myTestProc @ObjectCode @Alias @failoverLocale '' END

END

This works, but it returns two result sets when the @failoverLocale is used.  To work around this, I created a TABLE variable, ran the select statement inserting the value into the variable, and using IF EXISTS() to see if it's empty.  If it's not then I just select that result variable, and if it's empty I re-run the proc with the @failoverLocale. 

ALTER PROCEDURE dbo.myTestProc

@ObjectCode
@Alias
@Locale
@failoverLocale --Extra value to try if no records exist with the first locale
AS
BEGIN

DECLARE @Result TABLE(
	[ObjectCode] [bigint] NOT NULL,
	[Alias] [varchar] NOT NULL,
	[Locale] [varchar] NOT NULL
	)

INSERT INTO @Result
SELECT * from myTable
   WHERE
     ObjectCode	= @ObjectCode and
     Alias			= @Alias and
     Locale		= @Locale

IF EXISTS (SELECT * FROM @Result)
BEGIN
	SELECT * FROM @Result
END

ELSE IF(@failoverLocale = '')
BEGIN
	EXEC dbo.myTestProc 
		@ObjectCode
		@Alias
		@failoverLocale
		''
END
END

This also works, and returns only one result set, but this is a stored procedure that is run VERY frequently, and it has to be optimized for the best performance possible.  I'm really looking for a more elegant way of accomplishing what I need to.

Thanks,

Nick



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>