Insert stored procedure results into temp table - sql

I have a stored procedure that returns this result:
The way I call the stored procedure is:
Exec uspGetStandardUsingRoleandPhase '1908003'
I want to store these results into a temp table so I used insert into like this:
IF OBJECT_ID(N'tempdb.dbo.#tmp', N'U') IS NOT NULL
DROP TABLE #tmp
CREATE TABLE #tmp
(
startDate DATE,
endDate DATE,
strPhase NVARCHAR(50),
strBadgeNumber NVARCHAR(30)
)
INSERT INTO #tmp (startDate, endDate, strPhase, strBadgeNumber)
EXEC uspGetStandardUsingRoleandPhase '1908003'
But I get an error like this:
INSERT EXEC failed because the stored procedure altered the schema of the target table.

Hard to say without seeing the code to the stored procedure, but my guess is that the procedure also creates a temp table named #tmp. Try creating a temp table with a different name and running your INSERT EXEC into that, or post the code to the procedure so we can see it.

Worth noting this can also come up in SQL 2016 if you're using Query Store, and it happens to run a clean up during the procedure's execution. They suggest increasing the Query Store size to reduce the likelihood, but other than that, they're not planning to fix it for SQL 2016 (it's fixed in 2017)
https://support.microsoft.com/en-us/help/4465511/error-556-insert-exec-failed-stored-procedure-altered-table-schema

Related

Nested Stored Procedure

How can i insert values of a nested stored procedure into a table.
For example if i created a stored procedure like this.
Create procedure New
begin
create table #tmp
(
id int,
name varchar(50)
);
insert into #tmp
exec stored_procedure 1,2;
insert into #tmp
exec stored_procedure 1,2;
select * from #tmp
end
Now if I execute this command, SQL Server will display error:
insert into #table
exec New;
Does anyone have a solution for this problem? Please share
Right now you’re not returning any data from your procedure New. If you want it to return data for your calling code to insert you’ll need a select statement in it.
Eg add a line at the end:
SELECT * FROM #tmp;
Also, you can’t nest INSERT EXEC statements. See this answer for more details
You can't do a insert with de values returned by a Stored Procedure.
In your case the easiest way is to change de stored procedures by table functions.
You can find more about table functions here
My opinion is to make it simple if u can.

StoredProc manipulating Temporary table throws 'Invalid column name' on execution

I have a a number of sp's that create a temporary table #TempData with various fields. Within these sp's I call some processing sp that operates on #TempData. Temp data processing depends on sp input parameters. SP code is:
CREATE PROCEDURE [dbo].[tempdata_proc]
#ID int,
#NeedAvg tinyint = 0
AS
BEGIN
SET NOCOUNT ON;
if #NeedAvg = 1
Update #TempData set AvgValue = 1
Update #TempData set Value = -1;
END
Then, this sp is called in outer sp with the following code:
USE [BN]
--GO
--DBCC FREEPROCCACHE;
GO
Create table #TempData
(
tele_time datetime
, Value float
--, AvgValue float
)
Create clustered index IXTemp on #TempData(tele_time);
insert into #TempData(tele_time, Value ) values( GETDATE(), 50 ); --sample data
declare
#ID int,
#UpdAvg int;
select
#ID = 1000,
#UpdAvg = 1
;
Exec dbo.tempdata_proc #ID, #UpdAvg ;
select * from #TempData;
drop table #TempData
This code throws an error: Msg 207, Level 16, State 1, Procedure tempdata_proc, Line 8: Invalid column name "AvgValue".
But if only I uncomment declaration AvgValue float - everything works OK.
The question: is there any workaround letting the stored proc code remain the same and providing a tip to the optimizer - skip this because AvgValue column will not be used by the sp due to params passed.
Dynamic SQL is not a welcomed solution BTW. Using alternative to #TempData tablename is undesireable solution according to existing tsql code (huge modifications necessary for that).
Tried SET FMTONLY, tempdb.tempdb.sys.columns, try-catch wrapping without any success.
The way that stored procedures are processed is split into two parts - one part, checking for syntactical correctness, is performed at the time that the stored procedure is created or altered. The remaining part of compilation is deferred until the point in time at which the store procedure is executed. This is referred to as Deferred Name Resolution and allows a stored procedure to include references to tables (not just limited to temp tables) that do not exist at the point in time that the procedure is created.
Unfortunately, when it comes to the point in time that the procedure is executed, it needs to be able to compile all of the individual statements, and it's at this time that it will discover that the table exists but that the column doesn't - and so at this time, it will generate an error and refuse to run the procedure.
The T-SQL language is unfortunately a very simplistic compiler, and doesn't take runtime control flow into account when attempting to perform the compilation. It doesn't analyse the control flow or attempt to defer the compilation in conditional paths - it just fails the compilation because the column doesn't (at this time) exist.
Unfortunately, there aren't any mechanisms built in to SQL Server to control this behaviour - this is the behaviour you get, and anything that addresses it is going to be perceived as a workaround - as evidenced already by the (valid) suggestions in the comments - the two main ways to deal with it are to use dynamic SQL or to ensure that the temp table always contains all columns required.
One way to workaround your concerns about maintenance if you go down the "all uses of the temp table should have all columns" is to move the column definitions into a separate stored procedure, that can then augment the temporary table with all of the required columns - something like:
create procedure S_TT_Init
as
alter table #TT add Column1 int not null
alter table #TT add Column2 varchar(9) null
go
create procedure S_TT_Consumer
as
insert into #TT(Column1,Column2) values (9,'abc')
go
create procedure S_TT_User
as
create table #TT (tmp int null)
exec S_TT_Init
insert into #TT(Column1) values (8)
exec S_TT_Consumer
select Column1 from #TT
go
exec S_TT_User
Which produces the output 8 and 9. You'd put your temp table definition in S_TT_Init, S_TT_Consumer is the inner query that multiple stored procedures call, and S_TT_User is an example of one such stored procedure.
Create the table with the column initially. If you're populating the TEMP table with SPROC output just make it an IDENTITY INT (1,1) so the columns line up with your output.
Then drop the column and re-add it as the appropriate data type later on in the SPROC.
The only (or maybe best) way i can thing off beyond dynamic SQL is using checks for database structure.
if exists (Select 1 From tempdb.sys.columns Where object_id=OBJECT_ID('tempdb.dbo.#TTT') and name = 'AvgValue')
begin
--do something AvgValue related
end
maybe create a simple function that takes table name and column or only column if its always #TempTable and retursn 1/0 if the column exists, would be useful in the long run i think
if dbo.TempTableHasField('AvgValue')=1
begin
-- do something AvgValue related
end
EDIT1: Dang, you are right, sorry about that, i was sure i had ... this.... :( let me thing a bit more

Select Values From SP And Temporary Tables

I have a Stored Procedure in MSSQL 2008, inside of this i've created a Temporary Table, and then i executed several inserts into the temporary Table.
How can i select all the columns of the Temporary Table outside the stored procedure? I Mean, i have this:
CREATE PROCEDURE [dbo].[LIST_CLIENTS]
CREATE TABLE #CLIENT(
--Varchar And Numeric Values goes here
)
/*Several Select's and Insert's against the Temporary Table*/
SELECT * FROM #CLIENT
END
In another Query i'm doing this:
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
SELECT *
INTO #CLIENT
FROM OPENROWSET
('SQLOLEDB','Server=(local);Uid=Cnx;pwd=Cnx;database=r8;Trusted_Connection=yes;
Integrated Security=SSPI',
'EXEC dbo.LIST_CLIENTS ''20110602'', NULL, NULL, NULL, NULL, NULL')
But i get this error:
Msg 208, Level 16, State 1, Procedure LIST_CLIENTS, Line 43
Invalid object name '#CLIENT'.
I've tried with Global Temporary Tables and It doesn't work.
I know that is the scope of the temporary table, but, how can i get the table outside the scope of the SP?
Thanks in advance
I think there is something deeper going on here.
One idea is to use a table variable inside the stored procedure instead of a #temp table (I have to assume you're using SQL Server 2005+ but it's always nice to state this up front). And use OPENQUERY instead of OPENROWSET. This works fine for me:
USE tempdb;
GO
CREATE PROCEDURE dbo.proc_x
AS
BEGIN
SET NOCOUNT ON;
DECLARE #x TABLE(id INT);
INSERT #x VALUES(1),(2);
SELECT * FROM #x;
END
GO
SELECT *
INTO #client
FROM OPENQUERY
(
[loopback linked server name],
'EXEC tempdb.dbo.proc_x'
) AS y;
SELECT * FROM #client;
DROP TABLE #client;
DROP PROCEDURE dbo.proc_x;
Another idea is that perhaps the error is occurring even without using SELECT INTO. Does the stored procedure reference the #CLIENT table in any dynamic SQL, for example? Does it work when you call it on its own or when you just say SELECT * FROM OPENROWSET instead of SELECT INTO? Obviously, if you are working with the #temp table in dynamic SQL you're going to have the same kind of scope issue working with a #table variable in dynamic SQL.
At the very least, name your outer #temp table something other than #CLIENT to avoid confusion - then at least nobody has to guess which #temp table is not being referenced correctly.
Since the global temp table failed, use a real table, run this when you start your create script and drop the temp table once you are done to make sure.
IF OBJECT_ID('dbo.temptable', 'U') IS NOT NULL
BEGIN
DROP TABLE dbo.temptable
END
CREATE TABLE dbo.temptable
( ... )
You need to run the two queries within the same connection and use a global temp table.
In SQL Server 2008 you can declare User-Defined Table Types which represent the definition of a table structure. Once created you can create table parameters within your procs and pass them a long and be able to access the table in other procs.
I guess the reason for such behavior is that when you call OPENROWSET from another server it firstly and separately requests the information about procedure output structure (METADATA). And the most interesting thing is that this output structure is taken from the first SELECT statement found in the procedure. Moreover, if the SELECT statement follows the IF-condition the METADATA request ignores this IF-condition, because there is no need to run the whole procedure - the first met SELECT statement is enough. (By the way, to switch off that behavior, you can include SET FMTONLY OFF in the beginning of your procedure, but this might increase the procedure execution time).
The conclusions:
— when the METADATA is being requested from a temp table (created in a procedure) it does not actually exists, because the METADATA request does not actually run the procedure and create the temp table.
— if a temp table can be replaced with a table variable it solves the problem
— if it is vital for the business to use temp table, the METADATA request can be fed with fake first SELECT statement, like:
declare #t table(ID int, Name varchar(15));
if (0 = 1) select ID, Name from #t; -- fake SELECT statement
create table #T (ID int, Name varchar(15));
select ID, Name from #T; -- real SELECT statement
— and one more thing is to use a common trick with FMTONLY (that is not my idea) :
declare #fmtonlyOn bit = 0;
if 1 = 0 set #fmtonlyOn = 1;
set fmtonly off;
create table #T (ID int, Name varchar(15));
if #fmtonlyOn = 1 set fmtonly on;
select ID, Name from #T;
The reason you're getting the error is because the temp table #Client was not declared before you ran the procedure to insert into it. If you declare the table, then execute the list proc and use direct insert -
INSERT INTO #Client
EXEC LIST_CLIENTS

how can i drop a table which i have declared in my SP

like i declared a table...
declare #tempTable TABLE
(Id bigint identity(1,1),
bKey int,
DateT DateTime,
Addres nvarchar(max),
unit bigint)
and i want to drop it...but im stucked coz drop table n truncate are not working.
ani ideaaa...???
Table variables only live while they are in scope, in your case for the duration of the stored procedure. It will delete itself once the procedure completes.
You might be thinking of a temporary table:
CREATE TABLE #MyTempTable
There are differences between temporary tables and table variables:
http://sqlnerd.blogspot.com/2005/09/temp-tables-vs-table-variables.html
A better link:
http://www.sql-server-performance.com/articles/per/temp_tables_vs_variables_p1.aspx
You don't need to drop table variables (i.e. those that start with #)
You've declared the table as a table variable. It will only exist for the duration of the stored procedure. When the procedure ends, it is automatically "dropped" (ceases to exist is more accurate, as it never really existed in the way other tables do). You cannot drop them manually.
You created a temporary table which is saved in a variable. It only exists as long as the store procedure is being executed. When the SP has finished the temporary table ceases to exists and it's being deleted automatically.
edit:
you could try testing it by running the stored procedure and then try to run a select query on your #tempTable
why do you want to drop a table variable? scope of table variable is in declare stored procedure only...
check this article... Table Variables In T-SQL
UPDATE
Use #temptable as suggested by #Adam...
Then TRUNCATE TABLE #temptable, instead of DROP TABLE; this way no need to recreate it within loop.
In your SP, this will remove all the values from your declared table
DELETE FROM #tempTable

Why can't INSERT EXEC Stored procedures be nested?

I found a pretty good article detailing how to go about passing table data around and it mentions that the INSERT EXEC style table data sharing (http://www.sommarskog.se/share_data.html#INSERTEXEC) has the drawback of not being allowed to be nested?
In other words [in SQL Server 2005 at least], in the pseudocode below PROC1's INSERT EXEC would error out at runtime. I was wondering if anyone knows why this is.
CREATE PROC1
AS
--Fill table variable with data from somewhere
INSERT INTO #tbl EXECUTE spI_Return_Data
-- Do some stuff to the data
-- 'Return' it
SELECT * FROM #tbl
GO
CREATE PROC2
AS
--Fill table variable with data from PROC1
INSERT INTO #tbl EXECUTE PROC1
-- Do some stuff to the data
-- 'Return' it
SELEC * FROM #tbl
GO
Internal implementation restrictions.
If you need to capture the output of stored procedures, then those procedures should be a table valued function to start with. Ultimately you can work around the restriction by using CLR procedures.