开发者

SQL Server creating a temporary table from another table

开发者 https://www.devze.com 2022-12-19 04:11 出处:网络
I am looking to create a temporary table which is used as an intermediate table while compiling a report.

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 tab开发者_StackOverflow社区le 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


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?


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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号