How to export a table to a text file?
I need to get the INSERT script (structure and data) for an already existing table.
How to export a table to a text file?
I need to get the INSERT script (structure and data) for an already existing table.
You can run a insert script generator like this one:
http://sqltips.wordpress.com/category/insert-script-generator/
or a desktop tool like this:
http://www.shitalshah.com/sqlutils/
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
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
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):
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.