在函数(SQL Server)中执行动态sql时出错?

Cha*_*aka 19 sql function sql-server-2008

我创建一个函数来执行动态SQL并返回一个值.我得到"只有函数和一些扩展存储过程可以在函数内执行." 作为一个错误.

功能:

Create Function fn_GetPrePopValue(@paramterValue nvarchar(100))
returns int as
begin
declare @value nvarchar(500);

Set @SQLString  = 'Select Grant_Nr From Grant_Master where grant_id=' + @paramterValue

exec   sp_executesql
       @query = @SQLString,       
       @value = @value output

return @value   
end 
Run Code Online (Sandbox Code Playgroud)

执行:

Select dbo.fn_GetPrePopValue('10002618') from Questions Where QuestionID=114
Run Code Online (Sandbox Code Playgroud)

和:

Select fn_GetPrePopValue('10002618') from Questions Where QuestionID=114
Run Code Online (Sandbox Code Playgroud)

功能是正确调用还是函数不正确?

Ale*_*nko 8

您不能使用函数中的动态SQL,也不能调用存储过程.

Create proc GetPrePopValue(@paramterValue nvarchar(100))
as
begin
declare @value nvarchar(500),
        @SQLString nvarchar(4000)

Set @SQLString = 'Select @value = Grant_Nr From Grant_Master where grant_id = @paramterValue'

exec sp_executesql @SQLString, N'@paramterValue nvarchar(100)', 
       @paramterValue, 
       @value = @value output

return @value   
end 
Run Code Online (Sandbox Code Playgroud)