Vega Discoveries Forum

Welcome Guest Search | Active Topics | Log In | Register

sql function error handling Options
TechGuy
#1 Posted : Wednesday, February 24, 2010 2:01:54 PM
Rank: Advanced Member

Groups: Registered, Administrators

Joined: 8/17/2009
Posts: 43
Functions do not allow for Try-Catch blocks.
Function do not handle traditional error trapping very well.

My interest was in creating a function that would take care of number formatting for me. I wanted to restrict to two decimal places without embedding the code in every view I might create.

After a clear error on NOT being able to use a Try-Catch block in a function I used the following error trapping technique:
Code:

CREATE FUNCTION [dbo].[FORMATNUMBER_2DEC]
(
    @Value varchar(100)
)
RETURNS varchar(25)
AS
BEGIN

    Declare @Formatted varchar(100)
    Declare @err int
        
    Set @Formatted = cast(@Value as decimal(38,2))
    SELECT @err = @@error IF @err <> 0 Set @Formatted = @Value    
    
    RETURN @Formatted

END


This was GREAT! At least until I passed it a string value. Then I got an error returned rather than the Value passed in.

I then modified my code to the below sample and this works like a charm!
Code:

CREATE FUNCTION [dbo].[FORMATNUMBER_2DEC]
(
    @Value varchar(100)
)
RETURNS varchar(25)
AS
BEGIN

    Declare @Formatted varchar(100)

    If IsNumeric(@Value) = 1
        begin        
            Set @Formatted = cast(@Value as decimal(38,2))
        end
    Else
        begin
            Set @Formatted = @Value
        end
    
    RETURN @Formatted

END

Users browsing this topic
Guest
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Vega Discoveries Theme Created by Richard Hancock (aka-Tech Guy) (Home Page)
Powered by YAF 1.9.3 | YAF © 2003-2009, Yet Another Forum.NET
This page was generated in 0.053 seconds.