简体   繁体   English

从SQL存储过程返回临时表

[英]return temporary table from SQL stored procedure

I wrote this stored procedure: 我写了这个存储过程:

USE [FAB28]
GO
/****** Object:  StoredProcedure [dbo].[spPLCIOFilter2]    Script Date: 12/06/2011 08:00:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[spPLCIOFilter2]
(
    @filter1 VARCHAR(50) = '%',
    @filter2 VARCHAR(50) = '%',
    @slot VARCHAR(50) = '%' 
)
AS
BEGIN

    CREATE TABLE #temp
    ( 
         "PLC RIO" char(20)
         ,SIGNAL varchar(6)
         ,RACK char(2)
         ,SLOT char(2)
         ,POINT char(2)
         ,"CARD" char(20)
         ,TAG char(30)
         ,PROJ char(10)
         ,"DESCRIPTION" char(100)
         ,"ADDRESS" varchar(22)
     )

    INSERT INTO #temp
    SELECT
       [PLC] "PLC RIO"
      ,[SIGNAL] SIGNAL
      ,[RACK] RACK
      ,[SLOT] SLOT
      ,[POINT] POINT
      ,[CARD] "CARD"
      ,[TAG] TAG
      ,[PROJ] PROJ
      ,[DESCRIPTION] "DESCRIPTION"
      ,[ADDRESS] "ADDRESS"
    FROM [FAB28].[dbo].[PLC_TAGS2]
    WHERE [PLC] <> ''
    and [PLC] LIKE '%' + @filter1 + '%'
    and [PLC] LIKE '%' + @filter2 + '%'
    and [SLOT] LIKE '%' + @slot + '%'
    ORDER BY [PLC],[RACK],[SLOT],[POINT]

END

I want to return the temporary table #temp and return #temp doesn't work. 我想返回临时表#tempreturn #temp不起作用。 Also I want that the temp table will be dropped at the end of the function. 我也希望临时表将在函数末尾删除。

How can I do it? 我该怎么做?

You would add: 您将添加:

select * from #temp

at the end of the procedure. 在程序结束时。

In your SP, the temporary table looks redundant. 在SP中,临时表看起来多余。 You could just replace the insert statement with a select to return the data immediately. 您可以使用select替换insert语句以立即返回数据。

You don't return temp tables like this from stored procedures. 您不从存储过程返回这样的临时表。 You'd have to create the temp table first, call the proc, read the temp table afterwards: all on the same connection so it stays in scope 您必须先创建临时表,调用proc,然后再读取临时表:全部都在同一连接上,因此它处于作用域内

However, why not just SELECT in the stored proc and consume the result set normally? 但是,为什么不只是在存储的proc中进行SELECT并正常使用结果集呢? You don't need a temp table here 您不需要临时表

ALTER Procedure [dbo].[spPLCIOFilter2]
(
    @filter1 VARCHAR(50) = '%',
    @filter2 VARCHAR(50) = '%',
    @slot VARCHAR(50) = '%' 
)
AS
BEGIN
    SELECT
       [PLC] "PLC RIO"
      ,[SIGNAL] SIGNAL
      ,[RACK] RACK
      ,[SLOT] SLOT
      ,[POINT] POINT
      ,[CARD] "CARD"
      ,[TAG] TAG
      ,[PROJ] PROJ
      ,[DESCRIPTION] "DESCRIPTION"
      ,[ADDRESS] "ADDRESS"
    FROM [FAB28].[dbo].[PLC_TAGS2]
    WHERE [PLC] <> ''
    and [PLC] LIKE '%' + @filter1 + '%'
    and [PLC] LIKE '%' + @filter2 + '%'
    and [SLOT] LIKE '%' + @slot + '%'
    ORDER BY [PLC],[RACK],[SLOT],[POINT]
END

问题的第二部分-存储过程完成后,将自动删除在存储过程中创建的任何临时表-您无需执行任何其他操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM