Home > Database > Mysql Tutorial > body text

sql 自定义百分比转换小数函数代码

WBOY
Release: 2016-06-07 18:02:55
Original
1805 people have browsed it

sqlserver中自定义百分比转换小数函数,需要的朋友可以参考下。

代码如下:
--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')
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template