简体   繁体   中英

execute sp_executesql error

I have a formula.And formula is a nvarhcar like '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.' 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

You probably don't want to create a FUNCTION but a PROCEDURE because functions have the limitation that they generally cannot use EXECUTE . They are meant to be side-effect free and EXEC may be used to circumvent that guarantee.

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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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