SQL Server String PadLeft

I think this comes up a lot in day to day operations. Needing to pad the left hand side of a char/varchar field. T0 address this I made a handy dandy function that works similar to the padleft string function in .Net. There is a caveat to this code, if string length also sets the max length of string being returned. Below is the code, please test it for your application before putting it into production to make sure it has the behaviour that you need.

CREATE FUNCTION [dbo].[PadLeft](
    @StringLength INT,
@String VARCHAR(1000),
@PadChar CHAR(1)
)
RETURNS VARCHAR(1000)
AS
BEGIN
    DECLARE @Result VARCHAR(1000)
    DECLARE @PadLength INT;
    SET @PadLength = @StringLength LEN(@String)
    IF @PadLength <= 0
    BEGIN
        SET @Result =LEFT(@string,@StringLength)
    END
    ELSE
    BEGIN
        SET @Result =REPLICATE(@PadChar,@PadLength)+ @String
     END
    RETURN @Result
END

Advertisements

SQL Server Null Values ~ Into the Void (pun intended)

Null values can get some people rather confused writing queries. I hope I can shed some light on that. By default, SQL Server uses ANSI Nulls. This behavior says that any value compared to null is not equal to null.

if ‘a’=null
print ‘true’
else
print ‘false’

Returns false

Here is something interesting and if you are slightly devious, what about null compared to null?

if null=null
print ‘true’
else
print ‘false’

Returns false

if null is null
print ‘true’
else
print ‘false’

Returns true

Lets turn off ANSI_Null:

SET ANSI_NULL OFF;

if null=null
print ‘true’
else
print ‘false’ 

RETURNS TRUE!!!!!

if null is null
print ‘true’
else
print ‘false’ 

Returns true

According to MSDN, if you are trying to search for or compare null values using “is null” is recommended and will return consistent results.

If you are trying to create a query and want to include nulls in the result set you have to do it explicitly like this:
WHERE name = ‘Smith’ OR name IS NULL
Or if you want to exclude nulls:
WHEREname = ‘Smith’ OR name IS NOT NULL

If you want to be tricky you could do something like:

WHERE ISNULL (name,) = ‘Smith’

In London, they have signs that say “Mind the gap”, I say MIND THE NULLS!

One handy function to deal with nulls is Coalesce, which I describe here.