简体   繁体   中英

How to dump a table to a text file in SQL server? in sql Server 2005

How to export a table to a text file?

I need to get the INSERT script (structure and data) for an already existing table.

In SQL2k, try to read about bulk copy, the command should be bcp i think

examples from MS help file has something like ...

Exporting data from table to text file

bcp "SELECT au_fname, au_lname FROM pubs..authors ORDER BY au_lname" queryout Authors.txt -c -Sservername -Usa -Ppassword

Importing data from text file to table:

The command to bulk copy data from Newpubs.dat into publishers2 is:

bcp pubs..publishers2 in newpubs.dat -c -t , -r \n -Sservername -Usa -Ppassword

Alternatively, you can use the BULK INSERT statement from a query tool, such as SQL Query Analyzer, to bulk copy data:

BULK INSERT pubs..publishers2 FROM 'c:\newpubs.dat'
WITH (
   DATAFILETYPE = 'char',
   FIELDTERMINATOR = ',',
   ROWTERMINATOR = '\n'
)

Gath

In SQL Server 2005 Management Studio, you can use the Import/Export Wizard (not sure if you specifically needed a script, or simply a way to export the structure/data to a file, but this suggestion will do it without an actual script):

  • right-click on the database containing the table
  • select Tasks->Export Data
  • Choose a Data Source screen: (after the welcome screen) leave defaulted values, click Next
  • Choose a Destination: "Flat File Destination" for the Destination field. Then fill in the file name/path and the other options as you wish, click Next
  • Select Copy data..., click Next
  • Select the table to export, click Next
  • On the Save and Execute Package screen, you can just leave Execute Immediately selected, or if you'd like to save the resulting "script" as a SSIS package you can select that option also. Click Next, then Finish, to execute the export

  • Your resulting file will have the contents of the table. If you then need to "insert" this data into a different db you can use the "Import Data" option of the Wizard to import the data from the text file into the other database/table.

You can build the INSERT statement programatically by fetching the column info from the information_schema where each row of data describes a column:

SELECT   table_name, 
         ordinal_position, 
         column_name, 
         data_type, 
         is_nullable, 
         character_maximum_length 
FROM     information_schema.columns 
WHERE    table_name LIKE '%TableName%' 
ORDER BY ordinal_position 

For exporting data BCP is the tool and the BOL has several decent examples:

bcp AdventureWorks.Sales.Currency out Currency.dat -T -c

You can run a insert script generator like this one

or a desktop tool like this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM