sql在空格之间选择

时间:2014-11-26 15:17:59

标签: sql-server sql-server-2012

我的土地描述存储如下:

NW 1/4 6 7 5 E
NW 1/4 17 7 5 E

我需要输出如下:

NW6-7-5E
NW17-7-5E

因为第三组字符可以是1或2个字符,所以我不能使用LEN进行选择。我设法做到这一点:

Select Left(quartersection,2)+SUBSTRING(quartersection,8,CHARINDEX(' ',quartersection)-1)+'-'

我被困在哪里选择第3和第4空间以及第4和第5空间之间的物品。任何帮助表示赞赏。

感谢

2 个答案:

答案 0 :(得分:4)

试试这个。 Replace Right Left Len 字符串函数应该可以帮助你

DECLARE @a VARCHAR(50)='NW 1/4 17 7 5 E ' --NW 1/4 6 7 5 E

SELECT Replace(Replace(LEFT(@a, Len(@a)-3), ' 1/4 ', ''), ' ', '-')
       + Replace(RIGHT(@a, 4), ' ', '') 

输出NW17-7-5E

答案 1 :(得分:1)

使用Replace,Stuff和LEN功能:

create table #temp(quartersection varchar(20)) 

insert into #temp values('NW 1/4 17 7 5 E ')
insert into #temp values('NW 1/4 2 7 6 E ')

select * from #temp

SELECT Replace(Stuff(Replace(Replace(Rtrim(quartersection), '1/4', ''), '  ', ''), Len(Replace(Replace(Rtrim(quartersection), '1/4', ''), '  ', '')) - 1, 1, ''), ' ', '-')
FROM   #temp 

enter image description here