Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

sql - Update existing database values from spreadsheet

I have an existing MSSQL database where the values in some columns need updating according to a spreadsheet which contains the mappings of old data and new data.

The spreadsheet is like this:

       | OLD DATA      | NEW DATA      |
RECORD | A | B | C | D | A | B | C | D |
1      |OLD|OLD|OLD|OLD|NEW|NEW|NEW|NEW|
2      |OLD|OLD|OLD|OLD|NEW|NEW|NEW|NEW|

Where ABCD are the column names, which relate to the database, and OLD / NEW relates to the data.

Thus for each line (approx 2500 rows)

The database values that match OLD in each column, need to be changed to NEW

My current thoughts are to do it in a similar way to this: SQL Statement that Updates an Oracle Database Table from an Excel Spreadsheet

Essentially getting Excel to formulate a list of replace statements, though this feels like a horribly convoluted way to deal with the problem!

Is there a way to have SQL cycle though each row of the spreadsheet, check all records for a=old, b=old2, c=old3, d=old4 and then replace those values with the appropriate a=new, b=new2, c=new3, d=new4?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You shouldn't need to loop through each row in the spreadsheet. You can use the OPENROWSET command, like in the answer you linked to, to load the spreadsheet data into a sort of temporary table. You can then run a regular UPDATE statement against that table.

It would look something like this

UPDATE YourTable
SET YourTable.A = ExcelTable.NewDataA,
    YourTable.B = ExcelTable.NewDataB,
    YourTable.C = ExcelTable.NewDataC,
    YourTable.D = ExcelTable.NewDataD
FROM YourTable
INNER JOIN OPENROWSET('Microsoft.Jet.OLEDB.4.0',
         'Excel 8.0;Database=C:foldernamespreadsheetname.xls;',
         'SELECT column1name, column2name, column3name, column4name
          FROM [worksheetname$]') AS ExcelTable
ON YourTable.ID = ExcelTable.ID
WHERE (YourTable.A = ExcelTable.OldDataA
  AND YourTable.B = ExcelTable.OldDataB
  AND YourTable.C = ExcelTable.OldDataC
  AND YourTable.D = ExcelTable.OldDataD)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...