How to create temporary mirror table in another

Asked

Viewed 11,284 times

1

It is possible to create a mirror temporary table in another?

Example: Let’s say I have in my bank a table with 60 fields. I would like to create a temp with the name #table with the same table structure in the database, but without having to write the names of fields and types again. This is possible?

  • Already tried to create a view?

4 answers

2


Simply:

SELECT * INTO #tabela
FROM TabelaOrigem

2

To create an identical structure, but without any content, you can use the following form:

-- código #1
IF Object_ID('tempDB..#tabela','U') is not null DROP TABLE #tabela;

SELECT *
  into #tabela
  from minhatabela
  where 1 = 0;

Since the restriction of the WHERE clause is false, only the structure will be copied.

  • It says, when creating a table without data, I created it temporarily, but I can’t find it in the table tree. It exists, but I can’t see it. How I do it?

  • @pnet: Temporary tables are in the tempDB database. Local temporary tables are only visible in the current session. See documentation at https://msdn.microsoft.com/pt-br/library/ms174979.aspx#Anchor_4

1

  • This link may be a good suggestion, but your reply will not be valid if one day the link crashes. In addition, it is important for the community to have content right here on the site. It would be better to include more details in your response. A summary of the content of the link would be helpful enough! Learn more about it in this item of our Community FAQ: We want answers that contain only links?

  • I’m getting acquainted here, I changed the answer by being more objective with an example. I believe you can now contribute better to the community. Thanks for the advice

1

The action of creating a temporary table based on another table in SQL Server can be done during a select any. You can create by referencing the entire table or just a few fields.

Example:

SELECT * INTO #TEMP FROM TABELA

You can test the result immediately by checking the records in the temporary table.

SELECT * FROM #TEMP;

If you only want a sample of the table, you can impose a limit on the select of the type SELECT TOP 100 or SELECT TOP 1000 etc..

Remembering that it will not be "copied" any CONSTRAINT.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.