简体   繁体   English

SQL Server中的动态全局临时表

[英]Dynamic Global Temp Table in Sql server

I have a procedure that is creating a global temp table. 我有一个创建全局临时表的过程。 the problem is when you use more than one user at the same time give a problem because I cancel my temp table at the beginning , is there is one help me on about how to create an global temp table according to the session. 问题是当您同时使用多个用户时,由于我在一开始就取消了临时表,因此出现了问题,关于如何根据会话创建全局临时表有没有帮助我?

  1. If you truly want a "per session" table, then the names will have to be different (as they are global as their name implies), so use dynamic sql to generate an arbitrary name, perhaps based on spid: 如果您确实想要“每个会话”表,那么名称将必须不同(因为它们顾名思义是全局的),因此请使用动态sql生成一个任意名称,也许基于spid:

     declare @sql nvarchar(max) select @sql = N'select * into tempdb..##TempStudentRegistration' + convert(nvarchar(10), @@spid) + ' from Students' exec sp_executesql @sql 

(Note: Using Spids alone would assume the lifetime of the global temp table would be the same as the spid and that callers are not reusing spies; feel free to add as much additional uniqueness to that as your particular need dictates). (注意:单独使用Spids会假定全局临时表的生存期与spid相同,并且调用者不会重用间谍;请根据您的特殊需要为它添加尽可能多的唯一性)。

  1. If instead, you want a single global table, but just support multiple sessions writing to it, then consider recreating the global temp table or a locking mechanism to create the table if it doesn't exist: 如果相反,您只需要一个全局表,而仅支持向其写入的多个会话,则考虑重新创建全局临时表或使用锁定机制来创建该表(如果该表不存在):

     declare @rc int begin tran exec @rc = sp_getapplock 'mygloballock', 'exclusive', 'transaction' if (@rc >= 0) begin -- got the lock, if the table doesn't exist, create it if object_id('tempdb..##TempStudentRegistration') is null select top 0 * into ##TempStudentRegistration from Student exec sp_releaseapplock 'mygloballock' commit tran insert into ##TempStudentRegistration select * from Student end else begin raiserror('you did not get the app lock', 16, 1) end 
  2. Finally, if you don't actually need global temp tables (ie, you don't need to access the data from another session), consider using local temp tables (with a single # only), which are already scoped to the current session for you: 最后,如果您实际上不需要全局临时表(即,您不需要访问其他会话中的数据),请考虑使用本地临时表(仅包含单个#),该表已被限制在当前会话中为了你:

     select * into #TempStudentRegistration From Students 

If you're unsure about which type of temporary table you should be using, here's a great answer describing your options: https://stackoverflow.com/a/2921091/4313829 如果您不确定应该使用哪种类型的临时表,则以下是一个很好的答案来描述您的选项: https : //stackoverflow.com/a/2921091/4313829

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

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