这是字符串当前的两个示例:
6731-121-1
9552-3-1
Run Code Online (Sandbox Code Playgroud)
这就是我想要填充它们的样子
0006731-121-1
0009552-003-1
Run Code Online (Sandbox Code Playgroud)
所以我希望它们在第一个' - '之前用7个零填充,然后在第一个和第二个' - '之间填充3个零.
在SQL SELECT语句中实现此目的的最佳方法是什么.
SELECT RIGHT('0000000'
+ ISNULL(
LEFT(OE.exception_id, CHARINDEX('-', OE.exception_id)
- 1) ,
''
) ,7) + '-'
+ SUBSTRING(OE.exception_id, CHARINDEX('-', ( OE.exception_id )), 10) exception_id
Run Code Online (Sandbox Code Playgroud)
ParseName()可以是一个选项
例
Declare @YourTable Table ([YourCol] varchar(50))
Insert Into @YourTable Values
('6731-121-1')
,('9552-3-1')
Select *
,NewVal = right('0000000'+parsename(replace(YourCol,'-','.'),3),7)
+'-'
+right('000'+parsename(replace(YourCol,'-','.'),2),3)
+'-'
+parsename(replace(YourCol,'-','.'),1)
From @YourTable
Run Code Online (Sandbox Code Playgroud)
返回
YourCol NewVal
6731-121-1 0006731-121-1
9552-3-1 0009552-003-1
Run Code Online (Sandbox Code Playgroud)