Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server中的动态全局临时表_Sql_Sql Server - Fatal编程技术网

Sql server中的动态全局临时表

Sql server中的动态全局临时表,sql,sql-server,Sql,Sql Server,我有一个创建全局临时表的过程。问题是,当您同时使用多个用户时,由于我在开始时取消了临时表,因此会出现问题。关于如何根据会话创建全局临时表,是否有帮助 如果确实需要每个会话表,则名称必须不同,因为它们是全局的,正如名称所示,因此使用动态sql生成任意名称,可能基于spid: declare @sql nvarchar(max) select @sql = N'select * into tempdb..##TempStudentRegistration' + convert(nvarchar(10

我有一个创建全局临时表的过程。问题是,当您同时使用多个用户时,由于我在开始时取消了临时表,因此会出现问题。关于如何根据会话创建全局临时表,是否有帮助

如果确实需要每个会话表,则名称必须不同,因为它们是全局的,正如名称所示,因此使用动态sql生成任意名称,可能基于spid:

declare @sql nvarchar(max)
select @sql = N'select * into tempdb..##TempStudentRegistration' + convert(nvarchar(10), @@spid) + ' from Students'
exec sp_executesql @sql
注意:单独使用spid将假定全局临时表的生存期与spid相同,并且调用方没有重用SPIE;根据您的特殊需要,您可以随意添加更多的独特性

如果您需要一个全局表,只需支持多个会话写入它,然后考虑重新创建全局临时表或一个锁定机制来创建表(如果不存在):

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     

最后,如果您实际上不需要全局临时表,即,您不需要访问另一个会话的数据,请考虑使用仅具有单个单元格的本地临时表,这些表已经为您当前会话的范围:

select * into #TempStudentRegistration From Students

如果您不确定应该使用哪种类型的临时表,这里有一个很好的答案来描述您的选项:

您是如何创建临时表的?您是如何创建全局临时表的?选择*进入tempdb.dbo.tempstudenregistration From students谢谢,它在锁定机制中工作,但在使用本地临时表的第二种方法中,我遇到了一个问题,即我使用的透视表不能在本地临时表中工作。我只是问你们是否可以给我一个解决方案或其他方法来处理透视表