how to access the temporary table created inside stored procedure [vb6] - sql

I have a stored procedure inside which I am creating a temporary table.
My vb code will execute this stored procedure.
Is it possible to access the data in the temp table in vb6 after sp execution?

Use a global scope temporary table (they start with ## rather than #). These are shared between sessions. They go out of scope when the session that created them ends AND no other session is referring to them.
Temporary Tables in SQL Server
Creating and Modifying Table Basics
SQL Server 2005 and temporary table scope
Another option is a persistent temporary table (prefixed by TempDB..)

From Books Online:
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.

A temporary table created within a Stored Procedure is dropped when the Stored Procedure ends, so the answer is no.
If you really want to share a temporary table with the caller, you could do something like the following:
Conditionally create the temporary table in your Stored Procedure if it doesn't already exist
CREATE PROCEDURE MyProcedure AS
...
if object_id('tempdb..#temp') is null
BEGIN
CREATE TABLE #temp
(...)
END
...
Whenever you want to access the temp table from your caller, you should create the temporary table before calling the stored procedure.
By creating the temporary table conditionally in the Stored Procedure, it will work whether or not the caller creates the temporary table. The caller must of course create the temporary table with the correct structure, and DROP it when finished (or close the DB connection).

An option I've used in the past is to create the temp table prior to calling the stored proc that uses it. As long as you use the same open adodb connection it should work:
myAdoDBConn.Execute "CREATE TABLE #foo (ID integer)", , adCmdText
myADODBConn.Execute "StoredProcThatPopulatesFoo", , adCmdStoredProc
myAdoRecordset.Open "Select ID FROM #foo", myAdoDbConn, adOpenForwardOnly, adLockReadOnly
Do While Not myAdoRecordset.EOF
// do something with the record //
myAdoRecordset.EOF
Loop
In this example, the temp table stays available until you close the connection (myAdoDbConn).

Related

How can I create temp table and select it in a stored procedure?

Like the question title, how can I do that? I'm using Oracle SQL.
begin
-- create temp table here
-- sql query
-- select temp table here
end;
You can create the Global temporary table outside the procedure and use it in your procedure.
The data in a global temporary table is private, such that data inserted by a session can only be accessed by that session. The session-specific rows in a global temporary table can be preserved for the whole session, or just for the current transaction.
You can learn more about GTT from here.
But, looking at your problem It seems that you can use the private temporary table, that can be created in your session by you and deleted(automatically) once the session/transaction is completed.
But it is available from Oracle 18c onwards.
You can learn more about Private temporary table from here.

Stored procedure with global table

Is there any difference between stored procedure which uses global temporary table and one which does not in MS SQL database?
Global temporary table's scope is not limited to stored procedure, it can conflict with other procedures using same global temporary table(##TableName)
You can create Global temporary table in procedure, insert data and then see your data after store procedure execution.

Manipulations with temp tables on the same connection don't work with sprocs

I have a long-lived connection, on which the application creates a temp table and uses it to fetch some dynamic runtime data. To my understanding it should be possible to reference this temp table as long as it is done on the same connection. It is possible indeed when I do a bunch of raw queries, but it is not possible with sprocs. I use ADO.NET.
Am I missing something obvious here?
Works
CREATE TABLE #CustomerNames (CustomerName nvarchar(200) PRIMARY KEY)
DECLARE #CustomerName nvarchar(200)
SET #CustomerName ='Joe Baker'
INSERT INTO #CustomerNames (CustomerName) VALUES (#CustomerNames)
Doesn't work
EXEC customerNames_createTempTable
EXEC customerNames_addCustomerName 'Joe Baker'
where sprocs encapsulate the queries
EDIT: the solution is to create a temp table outside of a sproc using a query and then do all the manipulations with the table on the same connection using sprocs. This way the temp table doesn't go out of scope.
It's been a while since I worked with SQL Server, but as far as I know, temporary tables created within stored procedure only exist for the duration of the procedure execution. In other words, they are dropped when the procedure is finished.
The problem is the scope of validity of the temp tables. A temp table only exists inside the stored proc that creates the table and inside all the stored procs the first sproc is calling. So in your not working example the temp table is invalid after you call customerNames_createTempTable.
A solution is a global temp table. These temp tables are created with '#', e.g. ##CustomerNames. But beware: Global temporary tables are visible to all SQL Server connections. So you have to name them with a unique name.
BTW: It is good habit to explicitly drop the temp tables when you don't need them anymore.

Temporary Table Scope?

I am making use of temporary tables #tempTable in my stored procedure - that I make use to run my ASP.net Reports (Reporting services)
I am doing something like
eg. Code
SELECT * INTO #tempTable FROM Contacts WHERE ContactID < 10
Then I use something like
SELECT o.* FROM #tempTable t INNER JOIN Orders o ON t.ContactID =o.ContactID
to return values to my reports aka results for the stored procedure
I do not get rid of my #tempTable
i.e. I don't do
DROP TABLE #tempTable
I have read that the scope of temporary table is only for the stored procedure - so is doing the above necessary - if I dont do the above what problems will I get into in the future
First, local temporary tables created within a procedure are dropped once the procedure finishes. From the BOL on Create 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.
If your data access code is properly opening a connection, calling a stored procedure and then closing the connection, the temp table is created in the procedure is effectively destroyed.
I say "effectively" to bring up another point. I would not recommend dropping the temp table at the end of your procedure although I would add a check just before I created the temp table and drop it if exists (e.g. if object_id('tempdb..#Foo') is not null). The argument against dropping the temp table at the end is that by calling the Drop statement, you are forcing SQL Server to expend resources to destroy the table then and there while you wait for your procedure to end. If instead, you let it go out of scope, your procedure ends immediately and you let SQL Server destroy the table at a time of its own choosing.
The #Temp table is limited scope to YOUR SESSION and lifespan of the batch, meaning nobody else can see your temp table and anyone else can create their own #Temp table with the same name. Once your session or batch ends, SQL Server will clean up the temp table.
On another note the ##Temp table behaves like a normal table. Everyone can see it, and there cannot be more than 1 ##Temp table with the same name. SQL Server will clean these ##Temp tables when the server restarts.
It's considered good coding practice to explicitly drop every temporary table you create. If you are executing scripts through SQL Server Management Studio/Query Analyzer the temp tables are kept until you explicitly drop them or until you close the session.
In general, you're probably not going to have problems by not dropping temporary tables. The local temp table has session scope, or SP scope in your case. It will drop automatically when the session is closed or the SP completes.
However, you do increase the risk of problems by regularly following this practice. For example, if you don't use an SP, but submit your SELECT statement from ASP .net and leave the SQL Server connection open, the temp table will continue to exist. Continued use of the connection and other temp tables will result in tempdb growth over time.
I also support the other comments regarding the use of temp tables in this case. If you create a solution without temp tables, you'll probably have a faster report and avoid the DROP temp table command too.

SQL Server 2005 and temporary table scope

I've read around the subject of temporary tables and scope and all the answers i've seen don't seem to talk about one of my concerns.
I understand that a local temporary table's scope is only valid withing the lifetime of a stored procedure or child stored procedures. However what is the situation with regard to concurency. i.e. if i have a stored procedure that creates a temporary table which is called from two different processes but from the same user/connection string, will that temporary table be shared between the two calls to that one stored procedure or will it be a case of each call to the stored procedure creates an unique temporary table instance.
I would assume that the temporary table belongs to the scope of the call to the stored procdure but i want to be sure before i go down a path with this.
Local temporary tables (start with #) are limited to your session; other sessions, even from the same user/connection string, can't see them. The rules for the lifetime depend on whether the local temporary table was created in a stored procedure:
A local temporary table that is created in a stored procedure is dropped when the procedure ends; other stored procedures, or the calling process, can't see them.
Other local temporary tables are dropped when the session ends.
Global temporary tables (start with ##) are shared between sessions. They are dropped when:
The session that created them ends
AND no other session is referring to them
This command can be handy to see which temporary tables exist:
select TABLE_NAME from tempdb.information_schema.tables
And this is handy to drop temporary tables if you're not sure they exist:
if object_id('tempdb..#SoTest') is not null drop table #SoTest
See this MSDN article for more information.
The temporary table will be accesible to the instance of the procedure that creates it
The following script
Exec ('Select 1 as col Into #Temp Select * From #Temp')
Exec ('Select 2 as col Into #Temp Select * From #Temp')
Returns
Col
1
Col
2
Not
Col
1
2
Or an error because the table already exists.
The temporary table will also be accesible by any 'child' procedures that the initial procedure runs as well.
You might also think about using table variables. They have a very well-defined scope, and they are sometimes faster than their temporary table counterparts. The only problem with table variables is that they cannot be indexed, so some performance could be lost despite their nature. Check here for some more information on the subject.