سؤال

I've used the answer at Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

to pad a column with leading zeros in my case it's two zeros and I'm using this:

RIGHT('0'+ISNULL(REPLACE(<columnName>, '"', ''),''),2)

Data ranges from 1 to 99 but also includes a value of of 'UNK' for unknown which is truncated using this method.

Is there a way around this or should I be exploring a different solution as I'm dealing with text and numbers in the same column?

Cheers

J

هل كانت مفيدة؟

المحلول

(Second revision) Try this:

SELECT CASE WHEN LEN(ISNULL(<columnName>, '')) > 1
  THEN ISNULL(<columnName>, '')
  ELSE RIGHT ('00'+ ISNULL(<columnName>, ''), 2)
END

Sample input/output:

Input NULL  / Ouput '00'
Input 'UNK' / Ouput 'UNK'
Input '1'   / Ouput '01'
Input '99'  / Ouput '99'

نصائح أخرى

Regarding comment added below @bastos.sergio's answer:

SELECT CASE isnumeric(Val) AND len(Val) = 1 THEN '0' + Val ELSE Val END
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top