使用子字符串在SQL Server中获取正确的值

时间:2016-09-15 12:03:59

标签: sql-server substring

我在SQL Server中有这些数据:

1/2
1/4
2/23
12/13
1/10
...

我需要将这些更改为002,004,023,013,010,..

我只需要选择我的值的结束(RIGHT)部件号。我之前使用此代码获得了LEFT部分:

RIGHT('000' + LEFT(SheetNumber, CHARINDEX('/', SheetNumber) - 1), 3)

3 个答案:

答案 0 :(得分:6)

试试这个,

SELECT Right('000' + RIGHT(SheetNumber,LEN(SheetNumber) - CHARINDEX('/',SheetNumber) ), 3)

OR

SELECT RIGHT(REPLACE(@SheetNumber,'/','/000'),3)

答案 1 :(得分:3)

你几乎就在那里

Declare @YourTable table (SheetNumber varchar(50))
Insert Into @YourTable values
('1/2'),
('1/4'),
('2/23'),
('12/13'),
('1/10')

Select right('000'+substring(SheetNumber,CHARINDEX('/',SheetNumber) + 1,10),3)
 From @YourTable

返回

(No column name)
002
004
023
013
010

答案 2 :(得分:3)

首先,您需要获得正确的部分:

declare @table table (SheetNumber varchar(10))
insert into @table values ('1/2')
insert into @table values ('2/23')

select Right(SheetNumber, len(SheetNumber) - CHARINDEX('/',SheetNumber)) from @table

这会给你这个:

2
23

现在建立在它前面的垫0

declare @table table (SheetNumber varchar(10))
insert into @table values ('1/2')
insert into @table values ('2/23')

select Right('000' + Right(SheetNumber, len(SheetNumber) - CHARINDEX('/',SheetNumber)), 3) from @table

这会给你这个:

002
023