尝试返回sp_executesql的结果并获取“具有返回值的RETURN语句不能在此上下文中使用”

时间:2013-09-04 21:05:06

标签: sql-server tsql

我需要在函数中使用动态SQL,以便我可以执行SELECT * FROM searchAllFields('Pregnant')之类的操作。我知道在函数中不可能使用动态SQL,但我发现这个人找到了一个解决方法Getting an error when executing a dynamic sql within a function (SQL Server)?

但是当我尝试在mycode上应用他的工作时,我得到A RETURN statement with a return value cannot be used in this context.看起来我正在做同样的事情。为什么我在代码中出现错误?

ALTER proc [dbo].[searchTerm](@search nvarchar(max))
as
begin
declare @value nvarchar(500),
        @SQLString nvarchar(4000),
        @stmt nvarchar(max)

select @stmt = isnull(@stmt + ' or ', '') + quotename(name) + ' like @search'
from sys.columns as c
where c.[object_id] = object_id('dbo.table')

select @stmt = 'select @value = id from table where ' + @stmt

exec sp_executesql
    @stmt = @stmt,
    @params = N'@search nvarchar(max)',
    @search = @search,
    @value = @value output

    return @value 
end 

1 个答案:

答案 0 :(得分:0)

看起来这不起作用,因为你的函数返回inline table-valued function

对于此语法,函数定义后跟AS RETURN ( SELECT ... )而不是AS BEGIN... RETURN ... END