2015-09-16 85 views
0

我需要在我的表变量中插入数据到临时表,但它给我以下错误。SQL Server从表变量插入Temp表

消息208,级别16,状态0,过程sp_CreateScenario_q2,行70
无效的对象名称#tmpp1“。

下面是代码

IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL 
    DROP TABLE #tmpp1 

INSERT INTO #tmpp1 
    SELECT 
     [PlanningHierarchyId] 
     ,[ProductReferenceId] 
     ,[PlanningYear] 
     ,[PlanningSeason] 
     ,[UpdatedBy] 
    FROM 
     @paramTable 

有没有办法做到这一点?

回答

4

错误'无效的对象名称'#tmpp1'发生是因为您删除临时表,然后尝试插入它。

尝试使用:

IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL 
    DROP TABLE #tmpp1 
      SELECT 
       [PlanningHierarchyId] 
       ,[ProductReferenceId] 
       ,[PlanningYear] 
       ,[PlanningSeason] 
       ,[UpdatedBy] 
      INTO #tmpp1 
      FROM @paramTable 
2

插入时表已经存在使用SELECT INTO从被使用。当您尝试插入临时表时,临时表不存在。

参见:INSERT INTO vs SELECT INTO

IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL 
     DROP TABLE #tmpp1; 

       SELECT 
        [PlanningHierarchyId] 
        ,[ProductReferenceId] 
        ,[PlanningYear] 
        ,[PlanningSeason] 
        ,[UpdatedBy] 
        INTO #tmpp1 
       FROM @paramTable 
3

您要删除的表。或者用CREATE创建一个,或者用select * into代替insert into

IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL 
    DROP TABLE #tmpp1 

      SELECT 
       [PlanningHierarchyId] 
       ,[ProductReferenceId] 
       ,[PlanningYear] 
       ,[PlanningSeason] 
       ,[UpdatedBy] into #tmpp1 
      FROM @paramTable