2015-05-14 58 views
1

我期待編寫一個腳本,將改變表1至表2使用TSQL分離行成多行

表1

AccountNo名稱等領域

1  Mr T and Mrs M Lambert  xxx 

我需要將其重寫爲

表2

AccountNo分裂名稱等領域

1  a   Mr T Lambert    xxx 
    1  b   Mrs M Lambert   xxx 
+0

對不起你正確它對簡化 name字段是一個自由文本字段,可以包含像 麥當勞 瓊斯夫婦 史密斯先生 夫人皮博迪的事情 Mr L Thomas&Mrs P Smith 公司名稱 Jones and Smith 我需要拆分出哪裏有2人成一個記錄每個 但不是像瓊斯和史密斯公司這樣的公司名稱。 它可能是一個噩夢,但尋找任何幫助,我可以得到..........到目前爲止,我什麼都沒有.........仍然試圖讓我的頭靠近它 –

+0

我的建議是聘請一家數據清洗公司爲您做這件事,除非您的桌子足夠小以便用手操作,或者結果的質量不重要。你怎麼知道你是否真的在處理T先生http://en.wikipedia.org/wiki/Mr._T? –

回答

0

如果我是你,我會採取一些選擇的腳本語言編寫,並用其援助的轉換器。對我來說,看起來Perl或Ruby很適合這項任務。

例如,在Ruby中,這可能是這樣的:

require 'active_record' 

ActiveRecord::Base.establish_connection('postgresql://localhost/db') 
sql = ActiveRecord::Base.connection 

sql.begin_db_transaction 

# fetch the data from the source table 
sql.execute('SELECT * FROM source_table').each do |source_row| 
    # source_row is a hash now of the following form: 
    # { 'col_name_1' => 'col_value_1', 'col_name_2' => ... } 

    # prepare transformed rows array that will result in the destination table 
    transformed_rows = [ ] 

    # make up all the transformed rows you need, based on the source fields 
    transformed_rows << { 
    'another_col_1' => source_row['col_name_1'], 
    # ... 
    } 

    transformed_rows.each do |transformed_row| 
    # generate and execute the insert statement for every transformed_row 
    sql.execute("INSERT INTO destination_table(...) VALUES(...)") 
    end 
end 

sql.commit_db_transaction 

毫無疑問,它可以在SQL中實現,尤其是在像PL/SQL更豐富的方言,但文本分析(你顯然會相當做這裏有很多)並不是SQL強大的一面。因此,您將花費大量時間用不適合他們的語言來計算字符串操作。

希望有幫助!

0

您只需將from子句更改爲您的表名稱即可。

SELECT AccountNo, 
     person, 
     other 
FROM (VALUES(1,'Mr T and Mrs M Lambert','xxx')) AS yourTable (AccountNo,Name,Other) 
CROSS APPLY (SELECT REVERSE(SUBSTRING(REVERSE(Name),0,CHARINDEX(' ',REVERSE(name))))) CA(lastName) 
CROSS APPLY (
       SELECT PARSENAME(REPLACE(name,' and ','.'),1) person --first person 
       UNION ALL 
       SELECT PARSENAME(REPLACE(name,' and ','.'),2) + ' ' + lastName --second person 
      ) CA2 

結果:

AccountNo person                                     other 
----------- ------------------------------------------------------------------------------------------------------------------------------------------------------- ----- 
1   Mrs M Lambert                                   xxx 
1   Mr T Lambert                                   xxx 
+1

謝謝大家的意見,我已經用Stephans的評論來取得很好的效果.................它給了我一條可能解決我的問題的道路 –