Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sp_executesql and table output

I'm writing a stored procedure in SQL Server 2005, at given point I need to execute another stored procedure. This invocation is dynamic, and so i've used sp_executesql command as usual:

DECLARE @DBName varchar(255) 
DECLARE @q varchar(max) 
DECLARE @tempTable table(myParam1 int, -- other params)

SET @DBName = 'my_db_name'
SET q = 'insert into @tempTable exec ['+@DBName+'].[dbo].[my_procedure]'
EXEC sp_executesql @q, '@tempTable table OUTPUT', @tempTable OUTPUT

SELECT * FROM @tempTable

But I get this error:

Must declare the scalar variable "@tempTable".

As you can see that variable is declared. I've read the documentation and seems that only parameters allowed are text, ntext and image. How can I have what I need?

PS: I've found many tips for 2008 and further version, any for 2005.

like image 781
BAD_SEED Avatar asked Aug 29 '13 15:08

BAD_SEED


People also ask

What does Sp_executesql return?

sp_executesql will return 0 for success and any other number for failure.

What is difference between EXEC and Sp_executesql?

Exec vs sp_executesql The main difference between the EXEC or EXECUTE operators and the sp_executesql built-in stored procedure is that the EXEC operator is used to execute a stored procedure or a SQL command passed as a string or stored within a variable.

What is the use of Sp_executesql?

sp_executesql can be used instead of stored procedures to execute a Transact-SQL statement many times when the change in parameter values to the statement is the only variation.

What are the benefits of using Sp_executesql over EXEC?

sp_executesql allows for statements to be parameterized, Therefore It's more secure than EXEC in terms of SQL injection.


1 Answers

SQL Server 2005 allows to use INSERT INTO EXEC operation (https://docs.microsoft.com/en-us/sql/t-sql/statements/insert-transact-sql?view=sqlallproducts-allversions).

You might create a table valued variable and insert result of stored procedure into this table:

DECLARE @tempTable table(myParam1 int, myParam2 int);
DECLARE @statement nvarchar(max) = 'SELECT 1,2';
INSERT INTO @tempTable EXEC sp_executesql @statement;
SELECT * FROM @tempTable;

Result:

myParam1    myParam2
----------- -----------
1           2

or you can use any other your own stored procedure:

DECLARE @tempTable table(myParam1 int, myParam2 int);
DECLARE @statement nvarchar(max) = 'SELECT 1,2';
INSERT INTO @tempTable EXEC [dbo].[my_procedure];
SELECT * FROM @tempTable;
like image 169
Alex Vazhev Avatar answered Oct 05 '22 16:10

Alex Vazhev