下面为您介绍一个SQL中返回计算表达式的函数,该函数可以计算加、减、乘、除,但是不能算幂,供您参考,希望对您学习SQL中的函数能有有所帮助。
- CREATE FUNCTION dbo.GetExp(@pstrExpress AS VARCHAR(8000))
- RETURNS DECIMAL(18,6) AS
- BEGIN
- DECLARE @i INT,@j INT
- DECLARE @c1 CHAR(1),@c2 CHAR(1),@c VARCHAR(100)
- DECLARE @v1 DECIMAL(18,6),@v2 DECIMAL(18,6),@v DECIMAL(18,6)
- DECLARE @t TABLE(ID INT IDENTITY(1,1),s VARCHAR(100))
- DECLARE @s TABLE(ID INT IDENTITY(1,1),s VARCHAR(100))
- DECLARE @sv TABLE(ID INT IDENTITY(1,1),v DECIMAL(18,6))
- SET @pstrExpress = REPLACE(@pstrExpress,' ','')
- SELECT @i = 0,@j = LEN(@pstrExpress),@c2 = '',@c = ''
- WHILE @i<@j
- BEGIN
- SELECT @c1 = @c2,@i = @i+1
- SELECT @c2 = SUBSTRING(@pstrExpress,@i,1)
- IF CHARINDEX(@c2,'.0123456789') > 0 or (@c2 = '-' and @c1 IN('','*','-','+','/','('))
- BEGIN SELECT @c = @c + @c2 CONTINUE END
- IF @c <> '' BEGIN INSERT @t(s) SELECT @c SELECT @c = '' END
- IF CHARINDEX(@c2,')')>0
- BEGIN
- INSERT @t(s) SELECT s FROM @s WHERE ID > ISNULL((SELECT MAX(ID) FROM @s WHERE s IN('(')),0) ORDER BY ID DESC
- DELETE @s WHERE ID >= ISNULL((SELECT MAX(ID) FROM @s WHERE s IN('(')),0)
- CONTINUE
- END
- IF CHARINDEX(@c2,'+-)')>0
- BEGIN
- INSERT @t(s) SELECT s FROM @s WHERE ID > ISNULL((SELECT MAX(ID) FROM @s WHERE s IN('(')),0) ORDER BY ID DESC
- DELETE @s WHERE ID > ISNULL((SELECT MAX(ID) FROM @s WHERE s IN('(')),0)
- IF @c2 <> ')' INSERT @s(s) SELECT @c2
- CONTINUE
- END
- IF CHARINDEX(@c2,'*/')>0
- BEGIN
- INSERT @t(s) SELECT s FROM @s WHERE ID > ISNULL((SELECT MAX(ID) FROM @s WHERE s IN('(','+','-')),0) ORDER BY ID DESC
- DELETE @s WHERE ID > ISNULL((SELECT MAX(ID) FROM @s WHERE s IN('(','+','-')),0)
- INSERT @s SELECT @c2
- CONTINUE
- END
- IF CHARINDEX(@c2,'(')>0 INSERT @s SELECT @c2
- END
- IF @c <> '' INSERT @t(s) SELECT @c
- INSERT @t(s) SELECT s FROM @s ORDER BY ID DESC
- SELECT @i = 0,@j = MAX(ID) FROM @t
- WHILE @i < @j
- BEGIN
- SELECT @i = @i + 1
- SELECT @c = s FROM @t WHERE ID = @i
- IF @c = '(' CONTINUE
- IF @c NOT IN('*','-','+','/') BEGIN INSERT @sv(v) SELECT CONVERT(float,@c) CONTINUE END
- SELECT @vv2 = v FROM @sv DELETE @sv WHERE ID = (SELECT MAX(ID) FROM @sv)
- SELECT @vv1 = v FROM @sv DELETE @sv WHERE ID = (SELECT MAX(ID) FROM @sv)
- SELECT @v = CASE @c WHEN '+' THEN @v1 + @v2 WHEN '-' THEN @v1 - @v2
- WHEN '*' THEN @v1 * @v2 WHEN '/' THEN @v1 / @v2 END
- INSERT @sv(v) SELECT @v
- END
- SELECT @vv = v FROM @sv
- RETURN @v
- END
标题名称:SQL中返回计算表达式的函数
地址分享:http://www.shufengxianlan.com/qtweb/news24/477274.html
成都网站建设公司_创新互联,为您提供品牌网站制作、品牌网站建设、网页设计公司、企业建站、网站设计、营销型网站建设
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联