尝试返回sp_executesql的结果并获取"A RETURN statement with a return value cannot be used in this context"



我需要在函数中使用动态SQL,以便我可以做类似SELECT * FROM searchAllFields('Pregnant')的事情。我知道不可能在函数中使用动态 SQL,但我看到这家伙找到了解决方法在函数 (SQL Server) 中执行动态 sql 时出错?

但是当我尝试在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 

看起来这行不通,因为您的函数返回一个内联表值函数。

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

最新更新