用 TSQL 替换字符串中的每个第二个字符实例

Hec*_*res 5 regex t-sql sql-server replace

我有一个字段,其中包含定义地理围栏(多边形)的纬度/经度坐标字符串。每个都用逗号分隔。

例如:'纬度,经度,纬度,经度,纬度,经度'
例如:148.341158,-21.500773,148.341406,-21.504989,148.375136,-21.513174,148.401674,-21.535247,148.418044,-21.53 2767,148.408867,-21.511685,148.414075,- 21.508461,148.36968,-21.432567,148.349094,-21.438768,148.346862,-21.480187,148.341158,-21.500773,

我想将其与 MSSQL 中的地理类型一起使用(http://msdn.microsoft.com/en-us/library/bb933971.aspx

DECLARE @g geography;
SET @g = geography::STPolyFromText('POLYGON((-122.358 47.653, -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326);
SELECT @g.ToString();
Run Code Online (Sandbox Code Playgroud)

这似乎需要:“lat long,lat long,lat long”,即:一对之间没有逗号。

我无法更改源数据,因为它由供应商程序使用。我需要操作字符串以删除每 2 个逗号中的 1 个,或者如果失败,请在 TSQL 中使用正则表达式

chu*_*e x 0

您可以像下面这样推出自己的解析器。它使用字符串中的逗号来查找所有纬度/经度值。它使用以下模式将所有值连接在一起:lat long,lat long,...

declare @list varchar(max) 
declare @result varchar(max)
declare @word varchar(max)
declare @splitOn varchar(1)
declare @wpos int
declare @cpos int
declare @wordCount int

select @list = '148.341158,-21.500773,148.341406,-21.504989,148.375136,-21.513174,148.401674,-21.535247,148.418044,-21.532767,148.408867,-21.511685,148.414075,-21.508461,148.36968,-21.432567,148.349094,-21.438768,148.346862,-21.480187,148.341158,-21.500773,'
select @splitOn = ','
select @result = ''

select @cpos = 0
select @wpos = 1
select @wordCount = 1

while (@cpos <= len(@list))
begin
    select @cpos = charindex(@splitOn, @List, @cpos)
    if (@cpos < 1) select @cpos = len(@list) + 1

    select @word = substring(@list, @wpos, @cpos - @wpos)
    select @result = @result + ' ' + @word

    if ((@wordCount % 2) = 0 and (@cpos < len(@list))) select @result = @result + ','

    select @cpos = @cpos + 1
    select @wpos = @cpos
    select @wordCount = @wordCount + 1
end
select @result as result
Run Code Online (Sandbox Code Playgroud)

产生以下字符串:

148.341158 -21.500773、148.341406 -21.504989、148.375136 -21.513174、148.401674 -21.535247、148.418044 -21.532767、148.408867 -21 .511685, 148.414075 -21.508461, 148.36968 -21.432567, 148.349094 -21.438768, 148.346862 -21.480187, 148.341158 -21.500773