nic*_*App 6 sql database sql-server
场景:
我有一个table1(col1 char(5)); table1中的值可以是'001'或'01'或'1'.
需求:
无论col1中的值是什么,我都需要在5个字符串长度中将其与前导"0"连接,使其为5个字符长.
我申请的技术:
select right(('00000' + col1),5) from table1;
Run Code Online (Sandbox Code Playgroud)
我没有看到任何理由,为什么它不起作用?但事实并非如此.任何人都可以帮助我,我怎样才能达到预期的效果?
Mic*_*ren 12
由于您使用的是固定宽度的列,因此它的大小为5(带有空格).你需要修剪它:
DECLARE @table1 TABLE (col1 char(5))
INSERT INTO @table1 (col1) VALUES ('12345')
INSERT INTO @table1 (col1) VALUES ('1')
SELECT RIGHT('00000'+RTRIM(col1),5) FROM @table1
-- Output:
-- 12345
-- 00001
Run Code Online (Sandbox Code Playgroud)
或者varchar改为使用:
DECLARE @table2 TABLE (col1 varchar(5))
INSERT INTO @table2 (col1) VALUES ('12345')
INSERT INTO @table2 (col1) VALUES ('1')
SELECT RIGHT('00000'+col1,5) FROM @table2
-- Output:
-- 12345
-- 00001
Run Code Online (Sandbox Code Playgroud)