MS SQL Server中如果要根据需要动态保留小数位数没有太好的函数,所以自己写了一个
在数据库中创建标量值函数,如下
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: sgxcn
-- Create date: 2011/4/4
-- Description: <Description, ,>
-- =============================================
create 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);
if @DitIndex > 0
BEGIN
if @len < 1
SET @len = -1;
SELECT @ResultVar = SubString(@ResultVar, 1, @DitIndex + @len);
END
RETURN @ResultVar
END
GO
调用方法
select dbo.makedot(cast(1234.4546456 as varchar(50)), 2)