是否可以将表值参数传递给存储过程并返回表结果?

时间:2014-06-06 17:51:40

标签: sql sql-server sql-server-2008 tsql stored-procedures

我想创建一个存储过程,该过程接受一个表参数并返回一个单独的(模式)表结果集。

首先,这可能吗?

第二,我是在正确的轨道还是完全离开?

我的程序定义

USE MyDatabaseName

-- drop the procedure so we can recreate it
IF (OBJECT_ID('doit')) is NOT NULL DROP PROCEDURE doit
GO

-- drop and recreate the type in case we want to change how its defined
IF TYPE_ID(N'MyTableType') IS NOT NULL DROP TYPE MyTableType
CREATE TYPE MyTableType AS TABLE(keyvalue bigint NOT NULL, datevalue date NOT NULL)
GO

-- create procedure
CREATE PROCEDURE doit ( @indata MyTableType READONLY )
AS

-- Ultimately, real work will be done here that accumulates
-- a result set and returns it.  For now, we just return
-- a sub-set of what we were passed to see if this will
-- work...Which, it doesn't seem to.

RETURN SELECT top 100 keyvalue, datevalue FROM @indata

GO

我的主叫代码:

-- Call the doit procedure

declare @myargtable MyTableType

-- Gather my 'doit' argument
INSERT INTO @myargtable select top 1000 my_bigint_field, my_date_field from my_source_table;

-- This output is what I expect 'doit' to produce.
select top 100 * from @myargtable

-- Get a result table ready for the output of 'doit'
declare @results MyTableType

-- Store the results.
insert into @results EXEC doit @myargtable

-- I expect this to give me 100 records like above.
-- But, it gives me none.
select * from @results

2 个答案:

答案 0 :(得分:3)

从SP定义中删除RETURN,因此该行只是

SELECT top 100 keyvalue, datevalue FROM @indata

答案 1 :(得分:1)

存储过程只能返回int作为返回值。

也许您只想简单地SELECT将结果归还给他们:

CREATE PROCEDURE doit ( @indata MyTableType READONLY )
AS
   SELECT top 100 keyvalue, datevalue FROM @indata

   RETURN 0

或者使用表值函数:

CREATE FUNCTION doit ( @indata MyTableType READONLY )
RETURNS @t TABLE (
    keyvalue bigint,
    datevalue date )
AS

    insert into @t
    select top 100 keyvalue, datevalue
    from @indata

    return  

甚至是内联函数:

CREATE FUNCTION doit ( @indata MyTableType READONLY )
RETURNS TABLE AS RETURN (
    select top 100 keyvalue, datevalue
    from @indata
)