填充带有前导零的字符串,使其在SQLServer 2008中有3个字符长

填充带有前导零的字符串,使其在SQLServer 2008中有3个字符长

当第一次在SQLServer2008R2中创建它时,我有一个最多3个字符的字符串。

我想用前导零填充它,所以如果它的原始值是‘1’,那么新的值将是‘001’。或者,如果其原始值为“23”,则新值为“023”。或者,如果其原始值为‘124’,则新值与原始值相同。

我正在使用SQLServer2008R2。我将如何使用T-SQL来完成这个任务?


Cats萌萌
浏览 921回答 3
3回答

慕沐林林

如果字段已经是字符串,则此操作将有效。&nbsp;SELECT&nbsp;RIGHT('000'+ISNULL(field,''),3)如果你想让空显示为‘000’它可能是一个整数-那么你会想&nbsp;SELECT&nbsp;RIGHT('000'+CAST(field&nbsp;AS&nbsp;VARCHAR(3)),3)正如问题所要求的那样,这个答案只有在长度<=3时才有效,如果您想要更大的值,则需要将字符串常量和两个整数常量更改为所需的宽度。艾格'0000' and VARCHAR(4)),4

MM们

虽然问题是关于SQLServer2008R2的,但是如果有人正在阅读这个版本2012及以上版本,那么使用格式.您可以通过标准数字格式字符串或者是自定义数字格式字符串作为格式参数(谢谢瓦迪姆·奥夫钦尼科夫因为这个提示)。对于这个问题,例如,下面的代码DECLARE&nbsp;@myInt&nbsp;INT&nbsp;=&nbsp;1;--&nbsp;One&nbsp;way&nbsp;using&nbsp;a&nbsp;standard&nbsp;numeric&nbsp;format&nbsp;stringPRINT&nbsp;FORMAT(@myInt,'D3');--&nbsp;Other&nbsp;way&nbsp;using&nbsp;a&nbsp;custom&nbsp;numeric&nbsp;format&nbsp;stringPRINT&nbsp;FORMAT(@myInt,'00#');产出001 001

料青山看我应如是

下面是一种更通用的技术,用于向左填充到任何需要的宽度:declare @x&nbsp; &nbsp; &nbsp;int&nbsp; &nbsp; &nbsp;= 123 -- value to be paddeddeclare @width int&nbsp; &nbsp; &nbsp;= 25&nbsp; -- desired widthdeclare @pad&nbsp; &nbsp;char(1) = '0' -- pad characterselect right_justified = replicate(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;@pad ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;@width-len(convert(varchar(100),@x))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;+ convert(varchar(100),@x)但是,如果您处理的是负值,并填充前导零,则这和其他建议的技术都不起作用。你会得到这样的东西:00-123[可能不是你想要的]所以…您必须跳过一些额外的循环,这里有一种方法可以正确地格式化负数:declare @x&nbsp; &nbsp; &nbsp;float&nbsp; &nbsp;= -1.234declare @width int&nbsp; &nbsp; &nbsp;= 20declare @pad&nbsp; &nbsp;char(1) = '0'select right_justified = stuff(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;convert(varchar(99),@x) ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- source string (converted from numeric value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case when @x < 0 then 2 else 1 end ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-- insert position&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 ,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -- count of characters to remove from source string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;replicate(@pad,@width-len(convert(varchar(99),@x)) ) -- text to be inserted&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)应该注意到,convert()调用应指定[n]varchar具有足够的长度来保持转换结果的截断。
打开App,查看更多内容
随时随地看视频慕课网APP