2016-02-05 84 views
-1

我在爲表中的數據列在下面的格式:搜索和提取數據

(DeliveryMethod+NON;Installation_Method+NoInstallation;Services_Reference_ID+100118547,44444,33333;Service_ID+2222) 

(key+value;key+value;key+value;key+value;key+value;key+value;key+value;) 

我想搜索和提取該列的特定"value"基於特定"key""key+value"能在任何位置,如何使用SQL查詢來做到這一點?

+1

什麼RDBMS這是什麼? –

回答

0

下面是Oracle中的一種方法,正如我在本文中回答的:Oracle 11gR2: split string with multiple delimiters(add)。希望您可以將邏輯應用於您的RDBMS。請注意,此答案不只是從字符串中獲取值,而是嘗試解析字符串並返回值,以便它們可以像查詢結果集中的行一樣處理。這可能是你的情況矯枉過正。無論如何,這只是看待它的一種方式。

-- Original data with multiple delimiters and a NULL element for testing. 
with orig_data(str) as (
    select 'DeliveryMethod+NON;Installation_Method+NoInstallation;;Services_Reference_ID+100118547,44444,33333;Service_ID+2222' from dual 
), 
--Split on first delimiter (semi-colon) 
Parsed_data(rec) as (
    select regexp_substr(str, '(.*?)(;|$)', 1, LEVEL, NULL, 1) 
    from orig_data 
    CONNECT BY LEVEL <= REGEXP_COUNT(str, ';') + 1 
) 
-- For testing-shows records based on 1st level delimiter 
--select rec from parsed_data; 

-- Split the record into columns 
select regexp_replace(rec, '^(.*)\+.*', '\1') col1, 
     regexp_replace(rec, '^.*\+(.*)', '\1') col2 
from Parsed_data; 

結果:

enter image description here

具體回答你的問題,爲了得到基於鍵的值,從而獲得價值的最後一個查詢更改爲此其中關鍵是 '的Service_ID':

select value 
from (
    select regexp_replace(rec, '^(.*)\+.*', '\1') key, 
      regexp_replace(rec, '^.*\+(.*)', '\1') value 
    from Parsed_data) 
where key = 'Service_ID'; 

結果:

enter image description here

或僅提取出來使用正則表達式的字符串:

with orig_data(str) as (
    select 'Service_ID+2222;DeliveryMethod+NON;Installation_Method+NoInstallation;;Services_Reference_ID+100118547,44444,33333' from dual 
) 
select regexp_substr(str, '(.*?)Service_ID\+(.+?)(;|$)', 1, 1, NULL, 2) value 
from orig_data;