Pass database and table as parameters to process

Asked

Viewed 32 times

-2

I need to make a Stored Procedure of the following kind:

USE master
GO

CREATE PROCEDURE dbo.sp_DR @bd NVARCHAR(20), @VAL AS INT
AS

SELECT * INTO #TEMP FROM @bd where campo =@val 

SELECT campo1, campo2 from #temp
Em que @bd seria a base de dados e a tabela que iria utilizar.

How to pass this indication to the Stored Procedure?

If you put the BD table manually the SP is working as intended.

1 answer

2

You can create a dynamic query with the parameters and run with EXEC(), so for example:

CREATE PROCEDURE dbo.sp_DR @bd NVARCHAR(20), @VAL AS INT
AS

DECLARE @COMANDO nvarchar(1000)    
SET @COMANDO = 'SELECT * INTO #TEMP FROM ' +  @bd + where campo = ' + STR(@val)
EXEC (@COMANDO)

SELECT campo1, campo2 from #temp

So you can mount the whole query dynamically and then run. Note that as the @val parameter is INT need to convert, because all @COMMAND content is nvarchar

  • Thanks Ricardo. had already tried a similar approach, without success. I get the message: " (564 Rows affected) Msg 208, Level 16, State 0, Procedure dbo.sp_dr, Line 9 [Batch Start Line 0] Invalid Object name '#TEMP'. "

  • I took your tip with the following change: inside SP I created a table (#TEMP) with the same structure as the original, and in the command I used 'INSERT INTO #temp SELECT * FROM ' + @bd + ' WHERE field = ' + STR(@val). at the end DROP TABLE #temp

  • I think the error may be because, as it is a temporary table, it has been created in some context the part within the exec, which makes her not visible outside the exec, for being temporary can for example put the select also within the exec and take a test. Another change would be to create the table as "global Temporary", ie with ##TEMP. The downside is that since it’s global, it can conflict with another user, so it needed to generate a unique name before creating and preferably make a drop table at the end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.