2013-07-17 42 views
1

我想知道是否有方法從給定的字符串中提取位置名稱? 例如 字符串=「拉斯維加斯政黨在週末」或「巴黎時裝更新」從兩個字符串我想出來把儘可能 :「拉斯維加斯」或「巴黎」從字符串中提取位置名稱SQL

感謝

+3

你有一個包含預定義位置的表嗎? –

+0

@AlexFilipovici:+1;如果沒有參考表,我懷疑這樣的事情是不可能的! XD – AKDADEVIL

+1

哦,等等:用** RegEx **尋找以大寫字母開頭的單詞(至少可以用於英語字符串),可能會有一種非常混亂的方式,但它會非常容易出錯...... – AKDADEVIL

回答

0

假設你有一個包含一個表位置列表(例如locations (name varchar(100))),你可以這樣做:

select name from locations where @input like '%'+name+'%' 

哪裏@input是你輸入的字符串(「巴黎時裝更新」等)。

Here is a working example

順便說一句,如果您正在使用SQL Server,這裏是一招得到一個字符串輸出沒有while循環:

select @output = @output + ' ' + name 
from locations where @input like '%'+name+'%' 

updated fiddle

+0

謝謝 - 但是如果我的字符串包含多個位置可能是像'巴黎和倫敦時尚週' – user467710

+0

@ user467710它將工作:檢查出來:http://sqlfiddle.com/#!3/e21586/1 – Blorgbeard

+0

是的,我有一個表與預定義的位置表 – user467710

2

與預定義位置創建一個表:

CREATE TABLE locations 
    ( 
    [name] VARCHAR(50) 
); 

INSERT INTO locations 
      ([name]) 
VALUES  ('Paris'), 
      ('Las Vegas'), 
      ('London'); 

CREATE TABLE [test] 
    ( 
    [input] VARCHAR(max) 
) 

INSERT INTO [test] 
      (input) 
VALUES  ('Las Vegas parties at weekends'), 
      ('Paris fashion updates'), 
      ('Paris and London fashion weeks') 

然後與輸入字符串表加入吧:

SELECT 
    t.Input, 
    l.Name 
FROM 
    Locations AS l 
INNER JOIN test AS t ON t.Input LIKE '%' + l.Name + '%' 
ORDER BY 
    t.Input 

這裏的SQL Fiddle