Tuesday 30 October 2007

When Aliasing columns in SQL Server - don't use an actual column name

Stumbled across an interesting quirk in SQL Server.
I had a column called, "CallReference," which is a bigint. I wanted to pad the number with zero's to the left. So, 123 would become 00000123.

I did this:
cast(replicate('0', 8 - len(cast(callreference as varchar(8)))) + cast(callreference as varchar(8)) as varchar(8)) as CallReference

The strange thing is that by the time it got to my DataTable is was always treated as a number (depite me adding a cast as varchar).
The problem was caused by me using a column name as my alias that actually existed in the table. When I changed the name it would come back as string and be correctly padded in the DataTable.

No comments: