In a stored procedure, I have an EXEC statement; I want to store its results into a table.
First I create table parameter as:
DECLARE #MyTable AS TABLE
(
[Item1] INT,
[Item2] DECIMAL
)
Then I try to insert values as:
INSERT INTO #MyTable
EXEC [storedProcedure] #testitem = #testitem
My question: is this the right way to do that? Or do I need to use a dynamic query?
Because I read similar questions like this and they suggest to use a dynamic query.
You have to use a dynamic query.
DECLARE #Sql AS VARCHAR(MAX);
SET #Sql='EXEC storedProcedure #testitem = #testitem'
INSERT INTO #MyTable ([Item1], [Item2]) EXEC(#Sql)
SELECT * FROM #MyTable;
Asserting the above, I've been just tempted to read further... and found this older thread. I bet, it is helpful to analyze it further. Insert results of a stored procedure into a temporary table
Related
I have a user-defined table type tyAnalysisNumbers. I need to populate my user defined data type within a stored procedure with a SELECT statement and I am struggling to get that working within my stored procedure.
The following ways I have tried do not work
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO #MyTable
EXEC ('SELECT * FROM ' + #someTable);
I get this error:
An INSERT EXEC statement cannot be nested
I am unsure how to insert into my custom table via a select statement.
Can anyone help me accomplish this?
An INSERT EXEC statement cannot be nested
Above error is self explanatory. Please look at below scenario:
For example, we have one procedure which inserts data in table type and return result.
CREATE PROCEDURE uspInsertData1
AS
BEGIN
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO #MyTable
EXEC ('SELECT * FROM someTable');
select * from #MyTable
END
Now, let's say we have another procedure which will call above procedure and again insert data in another table.
CREATE PROCEDURE uspInsertData2
AS
BEGIN
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO sometable
EXEC uspInsertData1
END
Now, if you execute 1st procedure it will work fine but if you execute second procedure you will get this error.
An INSERT EXEC statement cannot be nested.
Because now you have nested EXEC statements.
I suggest to finish your work in single stored procedure if possible.
Try it like this:
DECLARE #MyTable tyAnalysisNumbers;
SELECT * INTO #Temp FROM #MyTable;
DECLARE #tblName AS SYSNAME = (SELECT name FROM sys.tables WHERE name = #someTable);
EXEC ('INSERT INTO #Temp SELECT * FROM ' + #tblName);
This also addresses the SQL Injection problem.
So I have declared a query within a varchar variable like:
DECLARE #sql VARCHAR(MAX) = 'select * from table'
I've also declared a temp table #Results that matches the column structure of the query.
I then call:
INSERT INTO #Results
EXEC (#sql)
The error I get is:
An INSERT EXEC statement cannot be nested.
I would also like to add that the query executes fine without the part
INSERT INTO #Results
What could be causing it? Any tips will be greatly appreciated
You can't stack together more than 1 INSERT INTO + EXEC, this is a limitation from SQL Server.
DECLARE #Test TABLE (Number INT)
INSERT INTO #Test (Number)
EXEC ('
CREATE TABLE #InnerTable (SomeColumn INT);
INSERT INTO #InnerTable (SomeColumn)
EXEC (''SELECT 1'');
SELECT 1;')
Msg 8164, Level 16, State 1, Line 4 An INSERT EXEC statement cannot be
nested.
If we remove the inner INSERT INTO + EXEC...
DECLARE #Test TABLE (Number INT)
INSERT INTO #Test (Number)
EXEC ('
CREATE TABLE #InnerTable (SomeColumn INT);
SELECT 1;')
Succeed!
There are multiple ways to workaround this limitation, however most of them will require modifying the EXEC content. You can find an exhaustive explanation here. The one I usually use with my procedures is sharing a temporary table. You need to create a temporary table outside the EXEC then load it inside. The table is still accessible outside the EXEC scope because it was created outside.
IF OBJECT_ID('tempdb..#Test') IS NOT NULL
DROP TABLE #Test
CREATE TABLE #Test (Number INT)
EXEC ('INSERT INTO #Test (Number) SELECT 1')
SELECT * FROM #Test
Downside of this approach is that the EXEC part might fail if the temporary table wasn't created or it was created with wrong column names or data types. Keep in mind that this won't work with variable tables, they need to be temporary (at least) to be accessible inside the EXEC scope.
I have a stored procedure that produces a script of insert statements as result.
I want to execute those statements so that I can fill the data in my table
For example :
SET NOCOUNT ON
INSERT INTO table ([UID], [Name])
VALUES ('1000002', 'name'),
('1000004', 'name2')
The stored procedure return this as result, I want to execute this script how do I do it?
If I understand correctly, the above code is printed out when the stored procedure runs.
I would start by modifying the stored procedure to take an output parameter. Stored procedures "return" integer values, not messages. They happen to print things out, but it is not good to depend on that behavior.
Then, you can simply do:
declare #str nvarchar(max);
exec <stored procedure> #str output;
exec #str;
I suspect there might be a better way to structure the code. Having stored procedures return code should only be done when you really understand what you are doing. I don't think I've ever written code where a stored procedure would return an insert statement. It seems better to run dynamic SQL in the stored procedure itself.
EDIT:
You can capture the output of the stored procedure as well:
declare #t table (id int identity, line nvarchar(max));
insert into #t(line)
exec(<stored procedure>);
Then, you can concatenate the values. You can use XML for this purpose, but I think this will work:
declare #str nvarchar(max);
set #str = '';
select #str = #str + line + ' '
from #t
order by id;
exec #str;
Thanx All of you but following is the way i should have done
USE db1;
SELECT *
INTO [table]
FROM [db2].[dbo].[table]
it helps me to copy a table
I have a new stored procedure that contain of following script:
Insert into #tmpTable
Exec dbo.SP_GetData '2016-11-01'
and above script causes a SQL Server error message
An INSERT EXEC statement cannot be nested.
because there is another INSERT EXEC inside the SP_GetData stored procedure and according to a few hours of reading on this error message, I can't have two INSERT EXEC or I will get that error.
I found several alternatives such as using inline query to insert into temp table and modify the existing SP_GetData stored procedure but both way can't work for me. In my case, it's a must to depend on SP_GetData as it involve many complicated process and must not be changed.
I just need to retrieve all data from the SP_GetData in my new stored procedure and return.
Please let me know what is my alternatives on this.
DECLARE #Query VARCHAR(100),#Date VARCHAR(100)
SELECT #Date = '2016-11-01'
SELECT #Query = 'dbo.SP_GetData '''+#Date+''''
INSERT INTO #tmpTable
EXEC (#Query)
I have stored procedure in which i store whole query inside string and then execute that. Now i want to store that execute result into temporary table for further processing.
Something like below :
Exec #Mainsql -- this returns me query result and i need to insert its result to temp table
I tried something like this:
Select * Into #TempTable
From
Exec #MainSQL
But It is lacking in syntax i guess.
So, i need result of mainsql into temptable
Try this:
CREATE TABLE #TempTable AS
Exec #MainSQL
You must create Temp Table first, You have to define all columns which will be returned from procedure, if you need to insert data using Stored Procedure:
CREATE TABLE #TempTable (Col1 INT, Col2 VARCHAR(10))
INSERT INTO #TempTable
EXEC [ProcedureName]
Another option is to use OPENROWSET, if you do not know returned columns :
SELECT * INTO #TempTable
FROM OPENROWSET('SQLNCLI', 'Server=.;Trusted_Connection=yes;', 'EXEC DBName.Schema.ProcedureName')