SQLServer2008 使用BCP導入導出表數據


--先開啟cmdshell

EXEC sp_configure 'show advanced options', 1

GO

RECONFIGURE

GO

EXEC sp_configure 'xp_cmdshell', 1

GO

RECONFIGURE

GO

 

/**導出指定表的文本文件 */
EXEC master..xp_cmdshell 'bcp dbname..tablename out D:\DT.txt -c -Sservername -Usa -Ppassword'

 

/**根據sql語句導出指定表的文本文件 */
EXEC master..xp_cmdshell 'bcp "select top 10 * from dbname..tablename" queryout d:\DT.txt -c -Sservername -Usa -Ppassword'

 

/**導出指定表的文本文件,指定分隔符,在-t后設置分隔符*/
EXEC master..xp_cmdshell 'bcp dbname..tablename out D:\DT.txt -c -t, -Sservername -Usa -Ppassword'

 

/**導入指定表的文本文件*/
EXEC master..xp_cmdshell 'bcp dbname..tablename in d:\DT.txt -c -Sservername -Usa -Ppassword'

 

注:

1.如果數據表里已有數據,此方法從文本導數據到數據表時,會在后面追加數據,不會先清空表。

2.如果導出時指定過分隔符,導入時用上面的導入方法會報錯。解決方法是不要指定分割符

3.此語句在sqlserver里執行時,不能換行,否則報錯

 

---------------

搞得這么麻煩,實際上后來才想到用SQLServer自帶的導出工具就行,

也就是將指定表復制到另一個自定義表里(如tablename2,仍存放在該數據庫),

如果需要恢復數據,可以通過

select * into tablename from tablename2

來恢復原表

此種方式在原表的某列列名改變后同樣適用

(所以該insert sql在插入值時應該是按照順序一一賦值,而不是按照列名)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM