简体   繁体   English

如何从我在SQL中运行的查询创建临时表?

[英]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. 我正在使用MS SQL,我没有权限创建表。 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. 您需要在tempdb上授予create,因为实际上在该数据库中创建了所有临时表。

Seek out your DBA to Grant you the appropriate privilege. 寻找您的DBA以授予您适当的权限。

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. 您的DBA的另一个好处是他或她可以解释如何正确创建和使用这些表。 :) :)

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. 我真的很喜欢Shawn的答案,但遗憾的是我认为订单查询是一个简单的连接。 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. 这样它就会在同一个会话中,您可以在订单查询中的所有查询中访问该表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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