Queens Dev
Some more ASP.NET

SQL Server Function - Remove Leading Characters

June 29, 2008 at 6:48 AM by bjsetegn

Here is a simple piece of code that will remove a specified character from the beginning of a string.  I don't know who the orginal author of this function is, I believe it has been around for quite awhile.  I made some changes to it so that if the first character is a minus sign '-' then it will trim leading characters around that minus sign.  This was to take care of changing '-0.57' to '-.57'.  There could be some extra logic thrown in there to trim around a user defined variable and not just '-' and to turn the feature on and off.  I didn't need it so I'll leave that up to somebody else.

This function works by replacing the character we want to trim with a space ' ' and then calling LTRIM on the string.  This will remove all spaces on the left and then the remaing spaces are replaced with the defined character.  NOTE: Because this replaces all spaces with the defined character this function should only be used on string without spaces in them.

Code 

/* ---------------------------------------------------------------------------------

PURPOSE

    The purpose of this function is to remove all leading characters from a string.

    This will also trim leading zeros around a minus sign

    Ex. Trim '0.57%' down to '.57%'

    Ex. Trim '-0.57%' down to '-.57%'

    Ex. Trim 'CCFFDDCCEE' remove C down to 'FFDDCCEE'

 

select dbo.ufn_TrimLeadingCharacters('-0001235005500', '0')

*/----------------------------------------------------------------------------------

 

ALTER FUNCTION dbo.ufn_TrimLeadingCharacters ( @Input VARCHAR(50), @LeadingCharacter CHAR(1) )

 

    RETURNS VARCHAR(50)

 

AS

BEGIN

 

Declare @returnValue as Varchar(50)

 

If SUBSTRING(@Input, 1, 1) = '-'

Begin

    Set @returnValue = Right(@Input, Len(@Input) - 1 )

    Set @returnValue = REPLACE(LTRIM(REPLACE(@returnValue, ISNULL(@LeadingCharacter, '0'), ' ')),

                   ' ', ISNULL(@LeadingCharacter, '0'))

    Set @returnValue = '-' + @returnValue

End

 

Else

Begin

    Set @returnValue = REPLACE(LTRIM(REPLACE(@Input, ISNULL(@LeadingCharacter, '0'), ' ')),

                   ' ', ISNULL(@LeadingCharacter, '0'))

END

 

 

RETURN @returnValue

 

End

Handle DB Null and Return Default in C#

May 9, 2008 at 2:21 AM by bjsetegn

 When retrieving data from a database you must handle null values.  The getDefaultIfDBNull method below will check if the value returned from the database is null.  If it is null then it will return the default value for that type of object.  For example if retrieving an int field from the database and passed a null value and TypeCode of Int32 it will return the default value of 0.  This helps streamline the checking for null proccess and ensures that all nulls are handled in a simliar way.

The Code:

        /// <summary>

        /// Checks if an object coming back from the database is dbnull.  If it is this returns the default

        /// value for that type of object.

        /// </summary>

        /// <param name="obj">Object to check for null.</param>

        /// <param name="typeCode">Type of object, used to determine what the default value is.</param>

        /// <returns>Either the object passed in or the default value.</returns>

        public static object getDefaultIfDBNull(object obj, TypeCode typeCode)

        {

            //If object is dbnull then return the default for that type.

            //Otherwise just return the orginal value.

            if (obj == DBNull.Value)

            {

                switch (typeCode)

                {

                    case TypeCode.Int32:

                        obj = 0;

                        break;

 

                    case TypeCode.Double:

                        obj = 0;

                        break;

 

                    case TypeCode.String:

                        obj = "";

                        break;

 

                    case TypeCode.Boolean:

                        obj = false;

                        break;

 

                    case TypeCode.DateTime:

                        obj = new DateTime();

                        break;

 

                    default:

                        break;

                }

            }

 

            return obj;

        }

 

This is a sample of a method that calls a stored procedure and needs to check for null.

 

        private void FillDetailInfo(int intDetailsId)

        {

            string conString = "";

            SqlDataReader dr;

 

            try

            {

                conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

                SqlConnection con = new SqlConnection(conString);

 

                SqlCommand cmd = new SqlCommand("uspGetDetails", con);

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.CommandTimeout = 100000;

                cmd.Parameters.AddWithValue("@intDetailsId", intDetailsId);

 

                con.Open();

                dr = cmd.ExecuteReader();

 

                //Get details

                if (dr.Read())

                {

                    _id = (int)dr["Id"];

                    _desc = (string)SecurityTools.getDefaultIfDBNull(dr["desc"], TypeCode.String);

                    _isActive = (bool)SecurityTools.getDefaultIfDBNull(dr["ACTIVE"], TypeCode.Boolean);

                }

 

                con.Close();

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

End Code