开发者

How to copy multiple row with single column update

I want to copy all the rows from my table with single column update.

Example.

Table County has 1000 rows and i w开发者_C百科ant to copy all the rows with single column update.

What is the proper way to do that ?


This question describes how to use clone to copy your record.

Assuming the 1000 records are already in an Enumerable called counties, we end up with

counties.each { |county|  
    county_copy = county.clone
    county_copy.col3 = update_function(county_copy.col3)
    county_copy.save
}


Assuming I understand you correctly, I'd do something like

INSERT INTO NewTable (Col1, Col2, Col3)
SELECT Col1, Col2, UpdateFunction(Col3)
FROM County

Where Col3 is the column you want to update, and UpdateFunction is the function you wish to use to update the column.

EDIT: Of course this is SQL, not Rails - I didn't look close enough at the question's tags :-)


@krunalshah You can build a array of hashes and pass that array to

Country.create(array)

,though it will execute multiple insert queries.

Other option use

connection.execute(<<-SQL)
    insert into country1 (col1, col2) 
    select col1, col2 from countries
  SQL
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜