简体   繁体   中英

How do I create a temporary table from a query that I am running in SQL?

I am using MS SQL and I don't have authority to create tables. What I like to do is create a temporary table from a query that I am running (called customer query) and use the temp table and link it to a new query called order query

How do I first create the temp table after I run my customer query, and how can I use that temp table in a second query called order query?

Will the temp table exist and gets updated every time I run my customer query?

You need to be granted create on tempdb as all temporary tables are actually created in that database.

Seek out your DBA to Grant you the appropriate privilege.

Temp tables only persist as long as you are connected to the scope of the session that created it. You can create a temp table that persists across all sessions but be wary as that be accessed then

An added benefit of your DBA is he or she can explain how to properly create and utilize those tables. :)

See my comment above. No need for a temp table. More than likely, what you need to do is simply a single query.

SELECT <colsNeeded>
FROM order  
INNER JOIN customer ON order.<customerID> = customer.<customerID>
WHERE order.X = ???

I really like Shawn's answer, but unfortunately I think it's under the assumption that the order query is a simple join. There can be many more things that he needs to do using the temporary table. If it's really needs to be that way, and you have permissions to create a temporary table, I would suggest create dynamic query of the first query and append it to the order query and execute both of them together. That way it'll be in the same session and you'll have access to that table in all the queries inside your order query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM