我为此创建了一个 min 函数。
create function dbo.fnMin( @P1 int, @P2 int)
returns int
as
begin
return case when @P1 > @P2 then coalesce(@P2,@P1) else coalesce(@P1,@P2) end;
end
go
它只返回两个值中较小的一个。然后你可以用它来做RIGHT后跟LEFT。在我看来,您实际上可以将它放在一个单独的 select 语句中,但按照我的方式拆分它会使其更具可读性。试一试...希望它有效!
select coalesce(left(SubStr, dbo.fnMin(nullif(charindex(' - ',SubStr),0),nullif(charindex(' · ',SubStr),0)) ),SubStr)
from (
select right([Caption],len([Caption])-(dbo.fnMin(nullif(charindex(' - ',[Caption]),0),nullif(charindex(' · ',[Caption]),0)))-3) as SubStr
from <YourTableName>
) t
内部 select 语句获取第一个“ - ”或“ · ”的所有值RIGHT。然后外部选择将获得第二个“ - ”或“ · ”
的所有内容我已经编辑了我的代码以不考虑第二个“-”或“·”
编辑:我不能使用 sqlfiddle,因为这个解决方案需要一个函数......但这是我能够在我的沙盒环境中运行的......
create table dbo.Interfaces (Caption varchar(1000))
go
insert into dbo.Interfaces
values
('CW-3D13-SW1 - GigabitEthernet1/0/1 · Uplink to 1K5-Core1'),
('CW-3D13-SW1 - FastEthernet1/0/43 · PHSA-MPAACT-3D13/16 - Cisco 2811 Fa 0/0'),
('c&w-internet-sw-ACB - GigabitEthernet1/0/24 · MPAACT PNG/UBC School of Medicine'),
('c&w-internet-sw-ACB - GigabitEthernet1/0/25 - Int-Link-CW-BCCA-Oak-St'),
('VPN 3030 - PCI Fast Ethernet')
go
create function dbo.fnMin( @P1 int, @P2 int)
returns int
as
begin
return case when @P1 > @P2 then coalesce(@P2,@P1) else coalesce(@P1,@P2) end;
end
go
select coalesce(left(SubStr, dbo.fnMin(nullif(charindex(' - ',SubStr),0),nullif(charindex(' · ',SubStr),0)) ),SubStr)
from (
select right([Caption],len([Caption])-(dbo.fnMin(nullif(charindex(' - ',[Caption]),0),nullif(charindex(' · ',[Caption]),0)))-3) as SubStr
from dbo.Interfaces
) t
go
这是结果......
igabitEthernet1/0/1
astEthernet1/0/43
igabitEthernet1/0/24
igabitEthernet1/0/25
CI Fast Ethernet
(5 row(s) affected)
如果您无法从这段代码中弄清楚......是时候打书先生了。;)