SQL Server全局临时表 - 无效的对象错误

时间:2016-01-19 14:29:24

标签: sql-server dynamic

SELECT  @SqlCmdEnd =',Member_Cd as x_Member_Cd,
            LOD.Val_Seq as x_GroupSort,
            vs.Member_RCID  as x_Org_Key,
            LOD.Val_Cd  as x_Level_Text,
            Type_RCID   as x_Type_RCID  
        into ##VS_Wide'+@l_Random+'

我们在存储过程中有一个动态查询,它使用如上所示的全局临时表。它适用于正常情况,但在加载,并发测试期间,我们遇到错误:

  

无效对象## VS_Wide12345

12345是使用以下脚本生成的随机数。

那么这个错误的可能原因是什么?任何有关这方面的帮助将不胜感激。

select @l_Random = replace(right(rand(), 5), '.', '')

1 个答案:

答案 0 :(得分:-1)

试试这个 -

DECLARE @l_Random CHAR(32) = REPLACE(NEWID(), '-', '')

DECLARE @SQL NVARCHAR(MAX)
SET @SQL = '
IF OBJECT_ID(''##VS_Wide' + @l_Random + ''') IS NOT NULL
    DROP TABLE ##VS_Wide' + @l_Random + '

SELECT 1 AS a
INTO ##VS_Wide' + @l_Random + '

SELECT * FROM ##VS_Wide' + @l_Random + '
'

PRINT @SQL
EXEC sys.sp_executesql @SQL

输出 -

IF OBJECT_ID('##VS_WideC016ADF003FD4254B6BBFB5053E9C956') IS NOT NULL
    DROP TABLE ##VS_WideC016ADF003FD4254B6BBFB5053E9C956

SELECT 1 AS a
INTO ##VS_WideC016ADF003FD4254B6BBFB5053E9C956

SELECT * FROM ##VS_WideC016ADF003FD4254B6BBFB5053E9C956