sql 自定义百分比转换小数函数代码
代码如下:
--CAST 和 CONVERT 函数 Percentage DECLARE @dec decimal(5,3), @var varchar(10),@hun decimal(5,1) set @dec=0.025 set @hun=@dec*100 set @var=cast(@hun as varchar(20))+'%' select @var ---小数转化为百分数函数 GetPercentageString ---涂聚文 Geovin Du if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPercentageString]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].[GetPercentageString] GO CREATE function GetPercentageString ( @dec decimal(10,3) ) returns varchar(20) AS BEGIN DECLARE @var varchar(10),@hun decimal(10,1) SET @hun=@dec*100 SET @var=cast(@hun as varchar(20))+'%' RETURN @var END GO --测试数据 涂聚文 Geovin Du SELECT [dbo].[GetPercentageString] (0.05) SELECT [dbo].[GetPercentageString] (0.25) SELECT [dbo].[GetPercentageString] (1.25) --1. 查询字符串中是否包含非数字字符 SELECT PATINDEX('%[^0-9]%', '1235X461') SELECT PATINDEX('%[^0-9]%', '12350461') --2. 查询字符串中是否包含数字字符 SELECT PATINDEX('%[0-9]%', 'SUYLLGoO') SELECT PATINDEX('%[0-9]%', 'SUYLLG0O') DECLARE @dec decimal(10,4), @var varchar(10),@hun decimal(10,4),@I INT,@K INT,@S VARCHAR(20) SET @var='5.23%' --SELECT @K=LEN(@var) --SELECT @S=LEFT(@var,@K-1) SELECT @S=RIGHT(@var,1) --SELECT @S SELECT @I=CHARINDEX('%',@S) IF @I>0 BEGIN SET @var=REPLACE(@var,'%','') SET @hun=CAST(@var AS decimal(10,4)) SET @dec=@hun/100 SELECT @dec END ELSE BEGIN SELECT @dec=NULL --'无效数据' END --百分数转化为小数函数 GetPercentageNumber ---涂聚文 Geovin Du if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPercentageNumber]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].[GetPercentageNumber] GO CREATE function GetPercentageNumber ( @var varchar(10) ) returns decimal(10,4) AS BEGIN DECLARE @dec decimal(10,4), @hun decimal(10,4),@I INT,@K INT,@S VARCHAR(20) SELECT @S=RIGHT(@var,1) --SELECT @S SELECT @I=CHARINDEX('%',@S) IF @I>0 BEGIN SET @var=REPLACE(@var,'%','') SET @hun=CAST(@var AS decimal(10,4)) SET @dec=@hun/100 --SELECT @dec END ELSE BEGIN SELECT @dec=NULL --'无效数据' END RETURN @dec END GO --测试数据 涂聚文 Geovin Du SELECT [dbo].[GetPercentageNumber] ('5.23%') SELECT [dbo].[GetPercentageNumber] ('%0.23')
相关推荐
ItBJLan 2020-06-16
专注前端开发 2020-10-21
苏康申 2020-11-13
vitasfly 2020-11-12
oraclemch 2020-11-06
liuyang000 2020-09-25
FellowYourHeart 2020-10-05
赵继业 2020-08-17
whyname 2020-08-16
Seandba 2020-08-16
dbasunny 2020-08-16
拼命工作好好玩 2020-08-15
langyue 2020-08-15
写程序的赵童鞋 2020-08-03
Accpcjg 2020-08-02
tydldd 2020-07-30
好记忆也需烂 2020-07-28