[SQL Server] Backup / Restore 特定 tables

當進行測試時, 有時為了測試不同程式是否得到相同結果(如Regression Test), 重覆restore DB 會是其中一個手段. 然而DBA 與developer 不是同一人時, 便會令測試變得麻煩. 故在測試時backup 指定table, 事後再restore 會是更快的方法.

在SQL server 中, 可以利用bcp command 進行table level 的backup / restore. 做法如下.

## Backup pledge table. ensure user have proper privilege.
bcp "select * from [DB_NAME].dbo.[TABLE_NAME]" queryout "[BKUP_FILE_NAME].bcp" -N -S <<Server Name>> -T -E -k

## Restore
bcp "[DB_NAME].dbo.[TABLE_NAME]" in "[BKUP_FILE_NAME].bcp" -N -S <<Server Name>> -T -E -b 10000

然而, 在restore 前, 但它有部份限制:

  • 會被key constrain 限制restore.
  • 須要Truncate table 才能夠進行restore.

當然, 如果只用作backup 又restore到不同table 的話, 還有更快的方法:

SELECT * INTO [NEW_TABLE_NAME] FROM [ORIGINAL_TABLE_NAME]

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.