How to import and export data in SQL Server?

Source: Internet
Author: User
Tags bulk insert

Data import and export will be used when SQL Server programming or management is involved. There are many ways to import and export data, which can be summarized based on my experiences in Project Creation:

1. SQL Server Import and Export wizard. This method is the most convenient.

Import wizard, Microsoft provides a variety of data Source drivers, including SQL Server Native Cliant, OLE DB For Oracle, Flat File Source, Access, Excel, XML, etc, it can basically meet the requirements of system development.

The export wizard also has the same number of target source drivers that can import data to different target sources.

This method is simple and easy for database administrators. During import, SQL Server will also help you create tables with the same structure.

2. Use. NET Code (for example, there is a txt or excel file that is read to the database)

2.1 The most common is to read the txt content cyclically and insert one by one into the Table.

2.2 read the entire set using the OLEDB driver.

The Code is as follows:

 
 
  1. String strOLEDBConnect = @ "Provider = Microsoft. Jet. OLEDB.4.0; Data Source = D: \ 1 \;
  2. Extended Properties = 'text; HDR = Yes; FMT = delimited '";
  3. OleDbConnection conn = new OleDbConnection (strOLEDBConnect); conn. Open ();
  4. SQLstmt = "select * from 1.txt ";
  5. // Read the data DataTable dt = new DataTable () in .txt ();
  6. OleDbDataAdapter da = new OleDbDataAdapter (SQLstmt, conn); da. Fill (dt );
  7. // Add or refresh rows in the specified range of DataSet to match the DataSet and able
  8. And IDataReader.
  9. If (dt. Rows. Count> 0)
  10. Foreach (DataRow dr in dt. Rows)
  11. {
  12. SQLstmt = "insert into MyTable values ('" + dr ..."
3. BCP can be used for importing and exporting large data volumes.

Syntax:

 
 
  1. bcp {[[database_name.][schema].]{table_name | view_name} | "query"}     
  2. {in | out | queryout | format} data_file      
  3. [-mmax_errors] [-fformat_file] [-x] [-eerr_file]    
  4. [-Ffirst_row] [-Llast_row] [-bbatch_size]    
  5. [-ddatabase_name] [-n] [-c] [-N] [-w] [-V (70 | 80 | 90 )]     
  6. [-q] [-C { ACP | OEM | RAW | code_page } ]   
  7. [-tfield_term]    
  8. [-rrow_term] [-iinput_file] [-ooutput_file] [-apacket_size]      
  9. [-S [server_name[\instance_name]]] [-Ulogin_id] [-Ppassword]      
  10. [-T] [-v] [-R] [-k] [-E] [-h"hint [,...n]"] 
Note the direction parameters for data import and export: in, out, queryout

For example:

 

For example:

 

4. bulk insert. T-SQL command that allows direct import of data

Syntax:

 
 
  1. BULK INSERT      
  2. [ database_name. [ schema_name ] . | schema_name. ] [ table_name | view_name ]         
  3. FROM 'data_file'       
  4.  [ WITH     (    [ [ , ] BATCHSIZE =batch_size ]      
  5. [ [ , ] CHECK_CONSTRAINTS ]      
  6. [ [ , ] CODEPAGE = { 'ACP' | 'OEM' | 'RAW' | 'code_page' } ]      
  7. [ [ , ] DATAFILETYPE =         
  8. { 'char' | 'native'| 'widechar' | 'widenative' } ]      
  9. [ [ , ] FIELDTERMINATOR = 'field_terminator' ]      
  10. [ [ , ] FIRSTROW = first_row ]      
  11. [ [ , ] FIRE_TRIGGERS ]      
  12. [ [ , ] FORMATFILE ='format_file_path' ]      
  13. [ [ , ] KEEPIDENTITY ]      
  14. [ [ , ] KEEPNULLS ]      
  15. [ [ , ] KILOBYTES_PER_BATCH =kilobytes_per_batch ]      
  16. [ [ , ] LASTROW =last_row ]      
  17. [ [ , ] MAXERRORS =max_errors ]      
  18. [ [ , ] ORDER ( { column [ ASC | DESC ] } [ ,...n ] ) ]      
  19. [ [ , ] ROWS_PER_BATCH =rows_per_batch ]      
  20. [ [ , ] ROWTERMINATOR ='row_terminator' ]      
  21. [ [ , ] TABLOCK ]      
  22. [ [ , ] ERRORFILE ='file_name' ]     )]   
Important parameters:

FIELDTERMINATOR, field separator

FIRSTROW: the first data row

ROWTERMINATOR: the row Terminator.

For example:

 
 
  1. BULK INSERT dbo.ImportTest   
  2. FROM 'C:\ImportData.txt'   
  3. WITH ( FIELDTERMINATOR =',', FIRSTROW = 2 ) 

5. OPENROWSET is also a T-SQL command, which contains DB connection information and other import methods. OPENROWSET can be used as a target table for INSERT, UPDATE, and DELETE operations.

Syntax:

 
 
  1. OPENROWSET   
  2. ( { 'provider_name', { 'datasource';'user_id';'password'     
  3.  | 'provider_string' }      
  4. , {   [ catalog. ] [ schema. ] object          
  5. | 'query'      }      
  6. | BULK 'data_file',         
  7.  { FORMATFILE ='format_file_path' [ <bulk_options> ]        
  8.  | SINGLE_BLOB | SINGLE_CLOB | SINGLE_NCLOB }} )<bulk_options> ::=     
  9. [ , CODEPAGE = { 'ACP' | 'OEM' | 'RAW' | 'code_page' } ]      
  10. [ , ERRORFILE ='file_name' ]     
  11. [ , FIRSTROW = first_row ]      
  12. [ , LASTROW = last_row ]      
  13. [ , MAXERRORS = maximum_errors ]      
  14. [ , ROWS_PER_BATCH =rows_per_batch ] 
For example:
 
 
  1. INSERT INTO dbo.ImportTest   
  2. SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',   
  3. 'Excel 8.0;Database=C:\ImportData.xls', 'SELECT * FROM [Sheet1$]' WHERE A1 IS NOT NULL) 

6. OPENDATASOURCE

Syntax:

 
 
  1. OPENDATASOURCE ( provider_name,init_string ) 
For example:
 
 
  1. INSERT INTO dbo.ImportTest   
  2. SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',   
  3. 'Data Source=C:\ImportData.xls;Extended Properties=Excel 8.0')...[Sheet1$] 

7. OPENQUERY. It is a query executed on the basis of the linked server. Therefore, before execution, you must set up the result set of link server. OPENQUERY to participate in DML operations as a table.

Syntax:

 
 
  1. OPENQUERY (linked_server ,'query') 
For example:
 
 
  1. EXEC sp_addlinkedserver 'ImportData',   
  2.    'Jet 4.0', 'Microsoft.Jet.OLEDB.4.0',   
  3.    'C:\ImportData.xls',   
  4.    NULL,   
  5.    'Excel 8.0'   
  6. GO  
  7.  
  8. INSERT INTO dbo.ImportTest   
  9. SELECT *   
  10. FROM OPENQUERY(ImportData, 'SELECT * FROM [Sheet1$]') 

The above is just a summary of some DB data import and export methods and some simple examples, hope to help you in practice.

Original article title: SQL Server data import and export Methods

Link: http://www.cnblogs.com/changbluesky/archive/2010/06/23/1761779.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.