在 SQL Server 2008 R2 中首次创建时,我有一个最长 3 个字符的字符串。
我想用前导零填充它,所以如果它的原始值为“1”,那么新值将为“001”。或者,如果其原始值为“23”,则新值为“023”。或者,如果其原始值为“124”,则新值与原始值相同。
我使用的是 SQL Server 2008 R2。我该如何使用 T-SQL 来做到这一点?
最佳答案
如果该字段已经是字符串,则这将起作用
SELECT RIGHT('000'+ISNULL(field,''),3)
如果您希望空值显示为“000”
它可能是一个整数——那么你会想要
SELECT RIGHT('000'+CAST(field AS VARCHAR(3)),3)
As required by the question this answer only works if the length <= 3, if you want something larger you need to change the string constant and the two integer constants to the width needed. eg
'0000' and VARCHAR(4)),4
关于sql-server - 用前导零填充字符串,使其在 SQL Server 2008 中为 3 个字符长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760900/