views:

936

answers:

3

I am looking to create a temporary table which is used as an intermediate table while compiling a report.

For a bit of background I am porting a VB 6 app to .net

To create the table I can use...

SELECT TOP 0 * INTO #temp_copy FROM temp;

This creates an empty copy of temp, But it doesn't create a primary key

Is there a way to create a temp table plus the constraints?

Should I create the constraints afterwards?

Or am I better off just creating the table using create table, I didn't want to do this because there are 45 columns in the table and it would fill the procedure with a lot of unnecessary cruft.

The table is required because a lot of people may be generating reports at the same time so I can't use a single intermediary table

+2  A: 

Do you actually need a Primary Key? If you are flitering and selecting only the data needed by the report won't you have to visit every row in the temp table anyway?

Mitch Wheat
I've found it useful to add indexes to temp tables on occasions with impressive results. There may be intermediate processing or JOINs etc
gbn
@gbn: sure. I add them when they are needed.
Mitch Wheat
You are correct it may be superfluous. I'll need to check each procedure. Originally the application used a single temp table with a primary key, but the no of users was small, now I am concerned that the temp table will become a bottleneck as there is many more users
DeveloperChris
A: 

You'd have to do one or the other:

  • add the PK/indexes afterwards
  • explicitly declare the temp table with constraints.

I'd also do this rather then TOP 0

SELECT * INTO #temp_copy FROM temp WHERE 1 = 0;
gbn
+2  A: 

By design, SELECT INTO does not carry over constraints (PK, FK, Unique), Defaults, Checks, etc. This is because a SELECT INTO can actually pull from numerous tables at once (via joins in the FROM clause). Since SELECT INTO creates a new table from the table(s) you specify, SQL really has no way of determining which constraints you want to keep, and which ones you don't want to keep.

You could write a procedure/script to create the constraint automatically, but it's probably too much effort for minimal gain.

gd047
Thanks for explaining that, pretty obvious I suppose once you see the reason.
DeveloperChris