动态sql里面存储了Procedure-sql server 2008

时间:2016-08-11 10:26:56

标签: sql sql-server

以下我试图执行时抛出错误

  

消息208,级别16,状态0,过程CallView,第11行   无效的对象名称'#table'。

CREATE PROCEDURE [dbo].[CallView]
AS
SET NOCOUNT ON; 
declare @name as varchar (max)

select @name = VIEW_NAME from ZBT_MAPPING_TABLE MT
INNER JOIN OUTPUT_DL DL ON MT.COMPID = DL.COMPID


-- insert to temp table
INSERT INTO #table
 (
    customerID,
    PRODUCT,
    PRODUCT_PRICE
    )
EXEC (N'select * from ' + @name)

当我执行它时

exec [dbo].[CallView]

将错误抛出

  

无效的对象名称'#table'。**

如果有人请说明这里出了什么问题,我们如何纠正它。 感谢

3 个答案:

答案 0 :(得分:1)

在使用之前,您需要先创建临时表#table

Insert

之前添加如下内容
Create Table #table
(
    customerID int Identity(1,1),
    PRODUCT varchar(100),
    PRODUCT_PRICE Decimal(18,2)
)

答案 1 :(得分:1)

试试这个,

CREATE PROCEDURE [dbo].[CallView]
AS
SET NOCOUNT ON;

DECLARE @name AS VARCHAR(max)

CREATE TABLE #table (
    customerID INT Identity(1, 1)
    ,PRODUCT VARCHAR(100)
    ,PRODUCT_PRICE DECIMAL(18, 2)
    )

SELECT @name = VIEW_NAME
FROM ZBT_MAPPING_TABLE MT
INNER JOIN OUTPUT_DL DL ON MT.COMPID = DL.COMPID

-- insert to temp table
INSERT INTO #table (
    customerID
    ,PRODUCT
    ,PRODUCT_PRICE
    )
EXEC (N'select * from ' + @name)

select *from  #table

drop table  #table

答案 2 :(得分:0)

您可以执行此操作,创建临时表

select * 
into #table
from MyTable

但不是

INSERT INTO #table
(
  customerID,
  PRODUCT,
  PRODUCT_PRICE
)