简体   繁体   English

执行sp_executesql错误

[英]execute sp_executesql error

I have a formula.And formula is a nvarhcar like '2+5+8/3' 我有一个公式,公式是nvarhcar像'2 + 5 + 8/3'

I want to make a function that after calculated my formula give me a result like 我想做一个函数,在计算出我的公式后给我一个结果

alter FUNCTION Calculate(@Formula NVARCHAR(100))
RETURNS FLOAT
AS
BEGIN
DECLARE @Result2 FLOAT,@Query NVARCHAR(50)
SET @Query=N'select @Result='+@Formula
execute sp_executesql @Query ,N'@Result float output',@Result=@Result2 OUTPUT
RETURN @Result2
END

function create successfully but I use the function 函数创建成功,但是我使用了函数

select dbo.Calculate('2+5+9') I get a error that 'Only functions and extended stored procedures can be executed from within a function.' 选择dbo.Calculate('2 + 5 + 9')我收到一个错误,“只能从函数中执行函数和扩展存储过程。” How can make a function like this?Thanks a lot 怎么能这样一个功能呢?

Thanks your answer but I will use it in a select query, my data like that 感谢您的回答,但我将在选择查询中使用它,我的数据是这样的

Name Formula Result
dd    2+3+5
gg    1+4+7
hh    2*8
jj    3*9
Kl    8*9

I have to calculate Result column a select like 我必须计算结果列选择

select Name,dbo.Calculate(Formula) as Result Is there another way to make it 选择Name,dbo.Calculate(Formula)作为结果还有另一种制作方法

You probably don't want to create a FUNCTION but a PROCEDURE because functions have the limitation that they generally cannot use EXECUTE . 您可能不想创建一个FUNCTION而是一个PROCEDURE因为函数具有局限性,即它们通常不能使用EXECUTE They are meant to be side-effect free and EXEC may be used to circumvent that guarantee. 它们无副作用,并且EXEC可以用来规避该保证。

You can something like bellow : 您可以像下面这样:

Create Proc Proc1

As

Begin

Select 'SQL Server'

End

Go

Create a Function 创建一个功能

Create Function dbo.Function1() Returns @Result Table
(

    Result Varchar(100)

 )

 As

Begin   

Insert @Result

SELECT * from OPENROWSET('SQLNCLI10', 'Server=<SERVERNAME>;UID=<LOGIN>;Pwd=     <PASSWORD>;',

        'Exec dbo.Proc1') AS C 

Return

 end

  Go

Execute function 执行功能

  Select * from dbo.Function1()

Hopes this helps you.... 希望这对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM