Insert data into a Temporary Table from a Stored Procedure - sql

I have a stored procedure called Sp_Ejecucion inside it create a temporary table with the following structure:
CREATE TABLE #CambioResult (FOL INT IDENTITY, RESULT INT)
and after that command to run another Sp as follows
BEGIN TRAN T1
DECLARE #vnCambiaRollTurnoResult INT = 0,
#vnReacomodoMarcajesResult INT = 0,
#Result INT = 0
BEGIN TRY
exec nsp_Exec #nClaEmp = #pnClaEmpresa,
#nClaTrab = #pnClaTrab,
END TRY
BEGIN CATCH
GOTO RETURN_ERROR
END CATCH
And the inside of the second stored I want to insert data to the table created in the first stored, How can I do it? what I have intended is the following:
INSERT INTO OBJECT_ID('tempdb..#CambioResult')
select #Error
pero marca error en esta parte OBJECT_ID

As you are inserting within the nested procedure, you will be able to reference the parent procedure temporary table #CambioResult inside nested procedure.
You have to change your INSERT statement in the nested procedure: nsp_Exec as given below:
INSERT INTO #CambioResult
SELECT ....
About Temporary table scope, reference msdn
Temporary tables are automatically dropped when they go out of scope,
unless explicitly dropped by using DROP TABLE:
A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. The table can be
referenced by any nested stored procedures executed by the stored
procedure that created the table. The table cannot be referenced by
the process that called the stored procedure that created the table

Related

Dependent object in the stored procedure is dropped and recreated again

I am trying to test a scenario when the dependent object in a stored procedure is dropped and recreated again.
I need a way to re-compile the stored procedure, without recreating it.
CREATE TABLE t1
(
c1 int
)
CREATE PROCEDURE tst_Proc
AS
BEGIN
INSERT INTO t1
VALUES (1)
END
DROP TABLE t1
CREATE TABLE t1
(
c1 int
)
Now the tst_Proc will be in invalid state, as the table t1 was dropped and recreated again.
Is there any way I can recompile the stored procedure - so that the object becomes valid?
I don't want to alter and recreate the stored procedure, as there is no change in the definition.

Access #TempTable declared in child procedure in parent procedure

I have nested stored procedures and I need to create a LOCAL TEMP TABLE in child procedure and be able to use it in the parent procedure.
EX:
Parent procedure:
EXEC ChildProcedure
SELECT * FROM #TempTable
Child procedure:
CREATE TABLE #TempTable (Field1 VARCHAR(1000),Field2 VARCHAR(1000))
INSERT INTO #TempTable (Field1,Field2) VALUES ('1','2')
When I try this, SQL says:
Invalid Object Name '#TempTable'
Is there any way to achieve this without GLOBAL TEMP TABLES ?
Well I think I finally found the answer to my question in https://msdn.microsoft.com/en-us/library/ms174979.aspx.
A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process that called the stored procedure that created the table.
So the answer to my own question is NO. I can't do that in that way.
The best approach (as #Damien_The_Unbeliever said) is to create the table in the parent procedure and populate it inside the child procedure.
Instead of Procedure you can create a table valued function like this and use a
Create Function ChiledFunction ()
Returns #TempTable Table (Field1 VARCHAR(1000),Field2 VARCHAR(1000)) AS
Begin
INSERT INTO #TempTable (Field1,Field2) VALUES ('1','2')
Return
end
and parent procedure is here
Create Procedure ParentProc
As
begin
select * from dbo.ChiledFunction()
end

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

cant set OUTPUT to return a table from another stored procedure

I am trying to create a stored procedure which returns a temp table to another stored procedure. However, I cannot seem to be able to set a table as an output variable. For instance:
#t table(ID int) output
as a parameters does not work. However the following does not complain:
#t int output
Is there a way to get one stored procedure to obtain a table generated by another stored proceedure? Thanks ahead of time!
The answer is No.
You could pass the name of the created table from one Stored Procedure to another and then in the second SP you can use the name to query thru the table.
Yes, you can achieve this by using a User Defined Table Type. All you need to do is
Create a User defined Table Type.
Create your first Stored Procedure to Accept a Table Type variable.
In your second procedure declare a Table Type variable, populate it with the data you want and call the first procedure by passing in the Table Type variable.
Here is a sample code.
1) Create the User Defined Table Type. Under the Programmability -- > Types -- > User Defined Table Types -- > Right click to create your table type
CREATE TYPE [schemaname].[Ttype] AS TABLE
(
EmployeeID int,
EmployeeName varchar(100),
)
GO
The above type is just an example, put in the columns that you require in it. Here Ttype is the Name of the TableType (you can name it as per your convenience)
2) Create your first stored procedure that will accept the Table type as variable so that you can use it.
CREATE PROCEDURE [schemaname].[StoredProcName]
#TableType Ttype READONLY
AS
BEGIN
-- Just an example on how to use the TableType.
INSERT INTO TableName(EmployeeId,EmployeeName)
SELECT EmployeeID,EmployeeName FROM #TableType
END
GO
The above Stored Procedure accepts a Table Type variable. The Ttype indicates that the #Tabletype variable is user defined table type. The READONLY indicates that no DML operations can be performed on the Table type parameter.
3) Now, create your second procedure that will pass the Table Type parameter to the above procedure created.
CREATE PROCEDURE [schemaname].[StoredProc2Name]
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Table as Ttype
INSERT INTO #Table(EmployeeID,EmployeeName)
SELECT EmployeeID,EmployeeName FROM schemaname.Employees
EXEC [schemaname].[StoredProcName] #Table
END
GO
In the above SP, you declare a variable named #Table which is of the Table Type (Ttype). Now you populate it with the data you need and then call the first procedure by passing in the #Table variable.

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