我希望编写一个将表1更改为表2的脚本。
表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 :(得分: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强大的一面。因此,您将花费大量时间用不太适合它们的语言来计算字符串操作。
希望有所帮助!
答案 1 :(得分: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