I need to convert int datafield to nvarchar with leading zeros
example:
1 convert to \'001\'
867 convert to \'000867\', etc.
thx.
One line solution (per se) for SQL Server 2008 or above:
DECLARE @DesiredLenght INT = 20;
SELECT
CONCAT(
REPLICATE(
'0',
(@DesiredLenght-LEN([Column])) * (1+SIGN(@DesiredLenght-LEN([Column])) / 2) ),
[Column])
FROM Table;
Multiplication by SIGN
expression is equivalent to MAX(0, @DesiredLenght-LEN([Column]))
. The problem is that MAX()
accepts only one argument...