GO
/****** Object: UserDefinedFunction [dbo].[makedot] Script Date: 2020/7/14 9:15:22 ******/
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- =============================================
-- Author: Wjf
-- Create date: 2020/7/13
-- Description: <Description, ,>
-- =============================================
ALTER FUNCTION [dbo].[makedot]
(
@var AS VARCHAR(50),
@len AS INT
)
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE @ResultVar AS VARCHAR(50);
DECLARE @DitIndex AS INT;
SELECT @ResultVar = @var; --cast(@var as varchar(50));
SELECT @DitIndex = CHARINDEX('.', @ResultVar);
--补位变量
DECLARE @Endvar AS NVARCHAR(50);
DECLARE @i INT;
--输入为小数时
IF @DitIndex > 0
AND @DitIndex < (@len + 1)
BEGIN
--位数小于有效位数
IF LEN(@ResultVar) < (@len + 1)
BEGIN
SET @Endvar = N'';
SET @i = 0;
WHILE @i < ((@len + 1) - LEN(@ResultVar))
BEGIN
SET @Endvar = @Endvar + N'0';
SET @i = @i + 1;
END;
SET @ResultVar = @ResultVar + @Endvar;
END;
ELSE
--四舍五入
--四舍五入
SELECT @ResultVar = cast ( CAST(ROUND(@ResultVar, @len + 1 - @DitIndex) AS numeric(38,10) ) AS varchar(38));
SELECT @ResultVar=SUBSTRING(@ResultVar,0, @len + 2)
END;
--输入为整数时
ELSE
BEGIN
BEGIN
--整数位小于有效位数
IF LEN(@ResultVar) < @len
BEGIN
SET @Endvar = N'.';
SET @i = 0;
WHILE @i < (@len - LEN(@ResultVar))
BEGIN
SET @Endvar = @Endvar + N'0';
SET @i = @i + 1;
END;
SET @ResultVar = @ResultVar + @Endvar;
END;
ELSE
--四舍五入取整
SELECT @ResultVar = ROUND(@ResultVar, 0);
END;
END;
RETURN @ResultVar;
END;