动态查询SELECT INTO #TmpTbl无法正常工作

时间:2015-09-17 13:13:13

标签: sql sql-server dynamic-sql

我遇到以下问题:

DECLARE @TmpMemberTypeCount NVARCHAR(4000)

SET @TmpMemberTypeCount =
    N'SELECT DISTINCT
        StoreID
        ,AgreedDate
        ,'+'''TotalCount'''+' as Type
        ,'+ @MemberTypeCols + '
      INTO #TmpMemberTypeCount
      FROM #TmpTbl as t

      PIVOT
      (
        SUM(CP_Count)
        FOR MemberShipType
        IN (' + @MemberTypePvt + ')
    ) as p
    GROUP BY StoreID
        ,AgreedDate'

EXEC (@TmpMemberTypeCount)

当我运行时,我没有收到错误,但是如果我尝试运行

SELECT * FROM #TmpMemberTypeCount

我得到的错误基本上表示该表尚未创建。

如果我将INTO #TmpMemberTypeCount更改为INTO TmpMemberTypeCount,一切正常。

是否无法将临时表与动态查询一起使用?

另一个注意事项是,如果我将EXEC更改为PRINT然后运行打印的内容,一切运行正常并创建临时表。

更新:

我需要使用#TmpTbl的原因是因为我正在为每个商店推出不同的膜类型。因此,如果有2个用户同时运行此报告,则user1的#TmpTbl中的列可能是:

StoreID,
AgreedDate,
Type,
User, -- MemberType1
Admin, -- MemberType2
Staff, -- MemberType3

user2的#TmpTbl中的列可能是:

StoreID,
AgreedDate,
Type,
Trainer, -- MemberType1
Chef, -- MemberType2
CoatCheck, -- MemberType3
Painter -- MemberType4

会员类型存储在@MemberTypeCols中,如Trainer, Chef, CoatCheck, Painter

3 个答案:

答案 0 :(得分:0)

当然,
当你执行这个命令时

EXEC (@TmpMemberTypeCount)

查询在新会话中发布,并带有新的身份。

临时表仅存在于创建的会话中。

执行命令时

SELECT * FROM #TmpMemberTypeCount

您正在另一个会话中执行查询 你必须使用真实的桌子,或全球临时的##

答案 1 :(得分:0)

DECLARE @TmpMemberTypeCount NVARCHAR(4000)
SET @TmpMemberTypeCount =
    N'SELECT DISTINCT
        StoreID
        ,AgreedDate
        ,'+'''TotalCount'''+' as Type
        ,'+ @MemberTypeCols + '
      INTO #TmpMemberTypeCount
      FROM #TmpTbl as t

      PIVOT
      (
        SUM(CP_Count)
        FOR MemberShipType
        IN (' + @MemberTypePvt + ')
    ) as p
    GROUP BY StoreID
        ,AgreedDate

   SELECT * FROM #TmpMemberTypeCount'   --<-- add this here 

EXEC (@TmpMemberTypeCount)

动态sql有自己的作用域在动态sql中创建的任何内容都不会对任何外部作用域可见

答案 2 :(得分:0)

在动态SQL中动态创建的临时表是在不同的会话中创建的,这就是为什么在您的情况下无法访问它(如Mattia Caputo所提到的)。

一个快速而简单的解决方法是在动态SQL之前创建临时表,然后只插入它:

if OBJECT_ID('tempdb..#TmpMemberTypeCount') is not null
    drop table #TmpMemberTypeCount

select *
into #TmpMemberTypeCount
from #TmpTbl
where 1 = 0

DECLARE @TmpMemberTypeCount NVARCHAR(4000)
SET @TmpMemberTypeCount =
    N'
INSERT INTO #TmpMemberTypeCount (cols....)
SELECT DISTINCT
        StoreID
        ,AgreedDate
        ,'+'''TotalCount'''+' as Type
        ,'+ @MemberTypeCols + '      
      FROM #TmpTbl as t

      PIVOT
      (
        SUM(CP_Count)
        FOR MemberShipType
        IN (' + @MemberTypePvt + ')
    ) as p
    GROUP BY StoreID
        ,AgreedDate'

EXEC (@TmpMemberTypeCount)