Solved

Problem using CREATE TABLE with/without EXEC

Posted on 2004-09-22
3
1,210 Views
Last Modified: 2007-12-19
I am creating a generic SP to update tables in my app. I pass in a field definition string, the field name string and a values string. Elements within the strings are delimited. - e.g. the field definition string could be:

[id] int,[date] datetime,consultant int,[note] ntext

The SP needs to copy records to a temporary table to begin with, and my intention was to create the temporary table using the field defn. string and the command:

EXEC('CREATE TABLE #tmpRec (' + @FieldDefstr + ')')

 - but any future refs to #tmpRec cause the error "Invalid object name '#tmpRec'."
I get the same error if I explicitly exclude the @FieldDefstr and use:

EXEC('CREATE TABLE #tmpRec ([id] int,[date] datetime,consultant int,[note] ntext)')

but all works ok when I do:

CREATE TABLE #tmpRec ([id] int,[date] datetime,consultant int,[note] ntext)

in the SP

This is no good though, as I must be able to create a temp table based whose structure is based on a SP parameter!

As an even simpler experiment, just try the foll. commands

DROP TABLE #tmprec
--CREATE TABLE #tmpRec ([id] int,[date] datetime,consultant int,[note] ntext)
EXEC('CREATE TABLE #tmpRec ([id] int,[date] datetime,consultant int,[note] ntext)')
SELECT * FROM #tmprec

(comment out lines 1..3 as reqd)

I can only imagine that the temp table created by EXEC is somehow inaccessible to the calling context...

Any suggestions?

STOP PRESS: since laboriously writing the above, I've just seen the BOL text:
"In the stored procedure or trigger, all statements that contain the name of a temporary table must refer to a temporary table created in the same stored procedure. The temporary table cannot have been created in a calling or called stored procedure, or in a string executed using EXECUTE or sp_executesql."

The qu therefore boils down to:
   - can I create a temp table based whose structure is based on a SP parameter?
   - or, must I use a normal table instead (and manage its creation/deletion)

Thanks

James.


0
Comment
Question by:jxstewart
3 Comments
 
LVL 15

Expert Comment

by:jdlambert1
ID: 12129151
You can create a temp table based on variable. Something like this:

DECLARE @sql nvarchar(4000)
SET @sql = 'CREATE TABLE #tmpREC(' + @FieldDefstr + ')'
EXEC sp_executesql @sql

Then you can reference #tmpREC in the rest of your code.
0
 
LVL 15

Accepted Solution

by:
mcmonap earned 125 total points
ID: 12131015
Hi jxstewart,

you could do this by making the temporary table a global temporary table, just add another hash to the start of your table name, this will mean that the table is assecible to any sql session for the duration of your sp running (it means if the table name is static only one session can run the sp at a time) - don't know if this is an issue?:

--begin code
DECLARE @FieldDefstr nVARCHAR(4000)

SET @FieldDefstr = '[id] int,[date] datetime,consultant int,[note] ntext'
EXEC('CREATE TABLE ##tmpRec (' + @FieldDefstr + ')')

SELECT * FROM ##tmpREC
--end code

or maybe:

--begin code
CREATE PROCEDURE usp_test @FieldDefstr nVARCHAR(4000)
AS
--DECLARE
EXEC('CREATE TABLE ##tmpRec (' + @FieldDefstr + ')')

INSERT INTO ##tmpREC VALUES (1,'2004-09-23',23,'this is a test')
SELECT * FROM ##tmpREC

DROP TABLE ##tmpRec
GO

usp_test '[id] int,[date] datetime,consultant int,[note] ntext'
--end code
0
 

Author Comment

by:jxstewart
ID: 12131613

I had tried jslambert's solution - sp_executesql  causes the same problem (probably for the same reason), as far as I can see.

The best solution seems to create a global temporary table - and indeed (no doubt until _just_ after I close this thread...) all works fine now.

Many thanks, mcmonap

James
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I wrote this interesting script that really help me find jobs or procedures when working in a huge environment. I could I have written it as a Procedure but then I would have to have it on each machine or have a link to a server-related search that …
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now