如何在SQL中的udf中执行SQL语句? [英] How can I execute an SQL statment inside a udf in SQL?

查看:356
本文介绍了如何在SQL中的udf中执行SQL语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数内执行类似(7 * 8/4 + 1)的字符串表达式如何在函数内实现它。

设置@variable =(@ EXpr)不是帮助,因为@variable正在考虑@Expr作为字符串变量而不是命令。

请注意:我将表达式附加为'Select'+ @Expr。

我在这做什么错。我在互联网上找到的大多数东西是没有用的,因为我不能在函数内部使用EXEC,因为只有在执行命令时才返回,而不是命令的结果。

怎么能我让@expr表现为一个sql命令,当涉及到行

SET @variable =(@ expr)。

请指导我完成



我尝试过:



声明@evaluated decimal(18,2)

声明@vexpr varchar(MAX)=((15 * 4)+ 1)

声明@formula varchar(max)= @ vexpr

SET @formula ='选择'+ @公式

SET @formula = REPLACE(@ formula,'''','')

SET @evaluated =(@ formula )



返回@evaluated;



代码发布任何线索或帮助



当我执行上述功能时,我收到如下错误: -

将数据类型varchar转换为数字时出错。

解决方案

  CREATE   TABLE  #TEMP(formula  NVARCHAR  500 ))
INSERT INTO #TEMP(公式)
VALUES ' ((15 * 4)+ 1)'),(' ((15/4)+ 1)'),(' ((15 * 4 )*(1 + 7))');

DECLARE @Grandtot NVarchar 500 ), @ Query NVARCHAR (MAX)

SELECT @Grandtot = STUFF(( SELECT ' + CAST(' + formula + ' AS FLOAT)' FROM #TEMP FOR XML
PATH(' '), type )。value(' 。' ' NVARCHAR(500)'), 1 1 ' ');

SET @ Query = N ' SELECT' + @ Grandtot + ' AS GrandTot';

EXEC @ Query );



输出:
- - -
GrandTot
- ---
545


I want to execute an string expression like (7*8/4+1) inside a function how can i achieve it inside a function.
Set @variable = (@Expr) is not helping, as @variable is considering @Expr as a string variable and not a command.
Please Note : I have append the expression as 'Select ' +@Expr.
What wrong am i doing here. Most of the things i found in the internet are of no use as i cant use EXEC inside a function as it returns only if the command is executed or not rather than the result of the command.
How can i make the @expr to behave as an sql command when it comes to the line
SET @variable = (@expr).
Please guide me through

What I have tried:

declare @evaluated decimal(18,2)
declare @vexpr varchar(MAX) = ((15 * 4) + 1)
declare @formula varchar(max) = @vexpr
SET @formula = 'Select ' +@formula
SET @formula = REPLACE(@formula , '''', '')
SET @evaluated = (@formula)

return @evaluated;

Code posted any leads or helps

When i execute the above function i get an error as below :-
Error converting data type varchar to numeric.

解决方案

CREATE TABLE #TEMP(formula NVARCHAR(500))
INSERT INTO #TEMP(formula ) 
    VALUES('((15 * 4) + 1)'),('((15/4) + 1)'),('((15 * 4) *(1+7))');

DECLARE @Grandtot NVarchar(500),@Query NVARCHAR(MAX)

SELECT @Grandtot=STUFF((SELECT '+CAST('+formula+' AS FLOAT)' FROM #TEMP FOR XML 
                     PATH(''),type).value('.','NVARCHAR(500)'),1,1,'');

SET @Query=N'SELECT '+@Grandtot+' AS GrandTot';

EXEC(@Query);



OUTPUT:
------
GrandTot
-----
545


这篇关于如何在SQL中的udf中执行SQL语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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