Tuesday, November 22, 2011

udfAddBackslashIfNec

Handy function for ensuring a given path ends in a backslash. 

After being burned enough times calling a path + filename without the necessary backslash at the end of the path, I decided to fortify all my code with this function. 

It simply checks for a backslash at the end.  If not present, it adds one.

USE Admin
GO

CREATE FUNCTION dbo.udfAddBackslashIfNec(
      @In varchar(1000)
      )
RETURNS varchar(1001)
AS
/*    DATE        AUTHOR            REMARKS
      11/22/11    PPaiva            Initial creation.

      USAGE
            SELECT dbo.udfAddBackslashIfNec('C:\blahblah')
            SELECT dbo.udfAddBackslashIfNec('C:\blahblah\')

      DESCRIPTION
            Returns @In with a backslash at the right, if necessary.

*/

BEGIN
      DECLARE @LenIn int,
                  @Out varchar(201)
     
      SET @LenIn = Len(@In)

      IF Right(@In, 1) = '\'  OR   @In = ''
            SET @Out = @In
      ELSE
            SET @Out = @In + '\'
     
     

      RETURN @Out

END