2010-10-16 120 views
2

我應該從地址字段中刪除以下內容。查找並替換SQL Server 2005中的字符串

  1. 將所有名爲'Flat'的單詞替換爲空白,同時刪除伴隨它的數字。

例如,我有一個名字叫'Flat 234 5th Street'。

它應該被替換爲第5街。

我把查詢作爲

select 
    ltrim(rtrim(substring ('Flat 123 5th Street', charindex('Flat ','Flat 123 5th Street') + 5, len ('Flat 123 5th Street')))) 

它返回

123街5號

現在,我必須找到是否直至空間的下一次出現,我有一個數值或不是。

如果數字,然後刪除它,否則離開它。

任何人都可以幫忙。

問候, 喝罵

是Marc_S,我不該那麼做(編輯)。 我無法用其他語言做。假設僅在T-SQL中執行。

嗨LittleBobbyTales,謝謝你的答案。 其實它不是一個標準的格式,我可能只有 平123

或平123五街1號主道

或1主平1

沒有規則,我們將有1號或Flat後的2個數字。 可能有也可能沒有數字。

它可以是任何一種方式。

+0

如果您發佈的代碼或XML,** **請在高亮文本編輯器的線,然後點擊在編輯器工具欄上的「代碼」按鈕(101 010)上進行很好的格式化和語法突出顯示! – 2010-10-16 14:56:17

+0

聽起來像一個正則表達式的完美匹配 - 不幸的是,SQL Server的T-SQL查詢語言在字符串操作/正則表達式匹配中並不是非常強大。你最好用像C#這樣的傳統編程語言來做這件事...... – 2010-10-16 15:02:55

+0

同意marc_s,但出於好奇,你能否給出更多你需要解析的地址字段的例子? – LittleBobbyTables 2010-10-16 15:22:37

回答

2

您可以使用標量值函數去除平坦部分。棘手的部分是如何檢查一個單詞是否是一個數字:@word like '%[^0-9]%'通過查找不是0-9的字符來實現。完整的示例:

if OBJECT_ID('fn_StripFlat') is not null 
    drop function fn_StripFlat 
go 
create function dbo.fn_StripFlat(
    @street varchar(150)) 
returns varchar(150) 
as begin 
    declare @word varchar(150) 
    declare @result varchar(150) 
    declare @cur int 
    declare @next int 
    declare @in_flat bit 

    set @cur = 1 
    while 1=1 
     begin 
     set @next = CHARINDEX(' ', @street, @cur) 
     if @next = 0 
      set @word = SUBSTRING(@street, @cur, len(@street) - @cur + 1) 
     else 
      set @word = SUBSTRING(@street, @cur, @next - @cur) 

     if @word = 'flat' 
      begin 
      set @in_flat = 1 
      end 
     else if @word like '%[^0-9]%' 
      begin 
      set @in_flat = 0 
      set @result = IsNull(@result + ' ','') + @word 
      end 

     if @next = 0 
      break 
     set @cur = @next + 1 
     end 
    return IsNull(@result,'') 
end 
go 

測試代碼:

declare @Streets table (street varchar(150)) 
insert @Streets 
      select 'Flat 234 5th Street' 
union all select 'Flat 123 456 5th Street 1st Main Road' 
union all select '1st Main Flat 1' 
union all select '5th Street 1st Main Road' 
union all select 'FlatStreet' 
union all select '' 

select street 
,  dbo.fn_StripFlat(street) 
from @Streets 

此打印:

Flat 234 5th Street      5th Street 
Flat 123 456 5th Street 1st Main Road 5th Street 1st Main Road 
1st Main Flat 1       1st Main 
5th Street 1st Main Road    5th Street 1st Main Road 
FlatStreet        FlatStreet