I need to use dynamic SQL w/in a function so that I can do things like SELECT * FROM searchAllFields('Pregnant')
. I know that it is not possible to use dynamic SQL within a function but I see that this guy has found a workaround Getting an error when executing a dynamic sql within a function (SQL Server)?
But when I try applying his work around on mycode I get A RETURN statement with a return value cannot be used in this context.
It seems like I am doing the exact same thing. Why am I getting that error in my code?
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