2017-10-05 29 views
1

我的數據看起來像這樣:如何檢索SQL Server中字符串的唯一特定部2012

PrimISOcodeGL 
99507 - Swimming Pools – installation & service – below ground - 1799 - Hazard 3 
18501 - Supermarkets - 5411 - Hazard 1 
91580 - Contractors Executive Supervisors - 1541 - Hazard 2 
10073 - Automobile Sales, Repair or Service Shop - 7539 - Hazard 2 

我怎麼只能檢索第一和第二之間的名字「 - 」?

因此,它應該是這樣的:

PrimISOcodeGL 
Swimming Pools 
Supermarkets 
Contractors Executive Supervisors 
Automobile Sales, Repair or Service Shop 

我想使用的功能像CHARINDEXLTRIMRTRIMLEN

+1

查找第一CHARINDEX。從那裏拿字符串+1直到下一個連字符的charindex。因此,這將是以charindex形式傳入的數字的子字符串。 – Amit

回答

2

下面是使用CHARINDEX和子的方法。

ONLINE DEMO

declare @table table (PrimISOcodeGL varchar(256)) 

insert into @table 
values 
('99507 - Swimming Pools - installation & service - below ground - 1799 - Hazard 3'), 
('18501 - Supermarkets - 5411 - Hazard 1'), 
('91580 - Contractors Executive Supervisors - 1541 - Hazard 2'), 
('10073 - Automobile Sales, Repair or Service Shop - 7539 - Hazard 2') 

select 
    ltrim(substring(substring(PrimISOcodeGL,charindex('-',PrimISOcodeGL) + 1,9999),1,charindex('-',substring(PrimISOcodeGL,charindex('-',PrimISOcodeGL) + 1,9999)) - 1)) 
from 
    @table 
+0

感謝您的快速回復。但是這個不會在第二次' - '後停止。 因此,我只需要'游泳池' – Oleg

+0

爲什麼在這裏使用9999? – Amit

+0

是的呢@Oleg看在線演示 – scsimon

相關問題