从存储过程执行具有多个表值参数的表值函数?

时间:2010-09-27 12:51:48

标签: sql sql-server sql-server-2008 code-reuse user-defined-functions

我有一个执行一些重复代码的存储过程,所以我决定将冗余代码变成一个表值函数。我遇到的问题是:

Msg 137, Level 16, State 1, Procedure Search, Line 98
Must declare the scalar variable "@myTVP".

我正在使用的SQL代码的一个简单示例是:

CREATE TYPE [dbo].textTable_type AS TABLE(
[text] [nvarchar] (36)
)

CREATE FUNCTION dbo.Search_fn
(@myTVP AS textTable_type READONLY)
RETURNS TABLE
AS
RETURN
(   SELECT * from @myTVP    )
GO

CREATE PROCEDURE [dbo].[Search]
@myTVP AS textTable_type READONLY
AS
BEGIN

SELECT * FROM dbo.Search_fn(@myTVP)

END
GO

DECLARE @TVP as textTable_type
INSERT INTO @TVP VALUES ('abc')
INSERT INTO @TVP VALUES ('123')
exec dbo.Search(@myTVP = @TVP)
GO

DROP FUNCTION Search_fn
DROP PROCEDURE Search

如果有人能提供任何见解,那就太棒了!

(如果您尝试运行此示例,则会有一些额外的错误,但它们源自包含的错误。问题是因为无法创建存储过程搜索。

谢谢。

1 个答案:

答案 0 :(得分:1)

这对我有用。 (添加了一些Go批处理分隔符并从存储过程调用中删除了括号)

如果这不适合您,那么数据库的兼容性级别是什么?

CREATE TYPE [dbo].textTable_type AS TABLE(
[text] [nvarchar] (36)
)
GO

CREATE FUNCTION dbo.Search_fn
(@myTVP AS textTable_type READONLY)
RETURNS TABLE
AS
RETURN
(   SELECT * from @myTVP    )
GO


CREATE PROCEDURE [dbo].[Search]
@myTVP AS textTable_type READONLY
AS
BEGIN

SELECT * FROM dbo.Search_fn(@myTVP)

END
GO

DECLARE @TVP as textTable_type
INSERT INTO @TVP VALUES ('abc')
INSERT INTO @TVP VALUES ('123')
exec dbo.Search @myTVP = @TVP 

GO

DROP FUNCTION [dbo].Search_fn
DROP PROCEDURE [dbo].Search
DROP TYPE [dbo].textTable_type