在函数内执行动态SQL时获取错误(SQL Server)? [英] Getting an error when executing a dynamic sql within a function (SQL Server)?

查看:516
本文介绍了在函数内执行动态SQL时获取错误(SQL Server)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

函数:

 创建函数fn_GetPrePopValue @paramterValue nvarchar(100))
返回int作为
begin
declare @value nvarchar(500);

Set @SQLString ='选择Grant_Nr从Grant_Master其中grant_id ='+ @paramterValue

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

return @value
end

执行:

 从问题中选择dbo.fn_GetPrePopValue('10002618')其中QuestionID = 114 


$ p $ 选择fn_GetPrePopValue(' 10002618')from Problem Where QuestionID = 114

函数调用是否正确或函数是否正确?

解决方案

您无法使用函数中的动态SQL,也不能调用
存储过程。 b
$ b

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

Set @SQLString ='Se lect @value = Grant_Nr从Grant_Master其中grant_id = @paramterValue'

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

返回@value
结束


I create a function to execute dynamic SQL and return a value. I am getting "Only functions and some extended stored procedures can be executed from within a function." as an error.

The function:

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 

The execution:

Select dbo.fn_GetPrePopValue('10002618') from Questions Where QuestionID=114

and:

Select fn_GetPrePopValue('10002618') from Questions Where QuestionID=114

Is the function being called properly or is the function incorrect?

解决方案

You cannot use dynamic SQL from a function, neither can you call stored procedures.

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 

这篇关于在函数内执行动态SQL时获取错误(SQL Server)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆