作为最终实现,这里是使用的完整功能。
ALTER FUNCTION [dbo].[_mpt_Format_Number]
(
@value SQL_VARIANT
, @money BIT = 0
)
RETURNS VARCHAR(max)
AS
BEGIN
DECLARE @ret VARCHAR(MAX)
--Check for NULL value
IF @value IS NULL BEGIN
-- Value IS NULL, return NULL
SET @ret = 'NULL'
END ELSE BEGIN
-- Value is NOT NULL
--Check for Numeric Value
IF ISNUMERIC(CONVERT(VARCHAR, @value)) = 0 BEGIN
--Value is NOT a Number, return NULL
SET @ret = 'NULL'
END ELSE BEGIN
--Value IS a Number
declare @isNeg BIT
declare @tmp varchar(max)
set @tmp = convert(varchar(max), round(cast(@value as money), 0), 1)
--Check if value is negative
if @value < 0 begin
--Value is Negative
set @isNeg = 1
--Remove the negative sign
set @tmp = replace(@tmp, '-', '')
end
--Remove the decimal plus any digits to the right of the decimal
set @tmp = left(@tmp ,len(@tmp) - 3)
--Is money set to True
if @money = 1 begin
--Pre-pend the dollar sign to value
set @tmp = '$' + @tmp
end
--Is isNeg set to True
if @isNeg = 1 begin
--Encapsulate the value with parenthesis
set @tmp = '(' + @tmp + ')'
end
SET @ret = @tmp
END
END
RETURN @ret
END