Old SQL habits

With each new version of SQL server some old SQL habits have to die.

In Dynamics GP we often find document numbering sequences that are padded with zeros to facilitate sorting/ordering and to “look normal” on printed documentation.

For example website orders may be imported via econnect into GP in the range:

W00000001 to W99999999

Now sometimes we need to generate sequences of those numbers or join with tables holding just the number and no prefix. There are very many examples of this, originating from various reasons all now in my TSQL code, embedded in stored procedures.

DECLARE @WebOrderID int
SET @WebOrderID=22
SELECT 'W' + REPLACE(STR(@WebOrderID, 7), SPACE(1), '0')

The above shows a contrived example, to give us the result: W0000022 by overlaying on a template.er

The above was the way we did things in the 90s, new kids these days (starting with SQL 2012), can use the much simpler to read and use  FORMAT command . A command that supports standard .NET format strings.

DECLARE @WebOrderID int
SET @WebOrderID=22
SELECT FORMAT(@WebOrderID,'W#00000000')

This produces  much more easily read SQL and assuming you don’t need to be backward compatible, it seems the best way to go forward.
Old habits die hard, I need to start thinking FORMAT for these kinds of problem where pre-SQL 2012 support is not required. 

Add comment