星期日, 12月 31, 2017

Extract binary data from MS SQL

在微軟範例 AdventureWorks,Production Schema 有個 Document 資料表,其中有一個欄位 Document 型態是 varbinary,儲存著 FileName 欄位所記載的檔案內容。藉由工具程式與適當的對話,可以取出內容復原:
  • bcp "SELECT Document FROM AdventureWorks.Production.Document WHERE FileName = 'Introduction 1.doc'" queryout /tmp/Introduction_1.doc -S localhost -U sa -P ...
  • Enter the file storage type of field Document [varbinary(max)]:
  • Enter prefix-length of field Document [8]: 0
  • Enter length of field Document [0]:
  • Enter field terminator [none]:
  • Do you want to save this format information in a file? [Y/n]
  • Host filename [bcp.fmt]:
雖然大多是預設值,唯一要特別注意的是 prefix-length,這裡有可能自作主張地把檔案前面多加了八位元組,讓 Word 開不起來或形成一堆亂碼的內容,因此必須輸入 0 覆蓋掉預設的 8 才能得到正常的檔案結果。在此之後,我們可以再利用 bcp.fmt:
  • bcp "SELECT Document FROM AdventureWorks.Production.Document WHERE FileName = 'Introduction 1.doc'" queryout /tmp/Introduction_1.doc -f bcp.fmt -S localhost -U sa -P ...
可惜的是除此之外,參數無法讓這段過程無需人工介入又産生正確的結果。另一個變通的做法:
  • bcp "SELECT Document FROM AdventureWorks.Production.Document WHERE FileName = 'Introduction 1.doc'" queryout /tmp/Introduction_1_with_prefix.doc -n -S localhost -U sa -P ...
  • tail --bytes=+9 /tmp/Introduction_1_with_prefix.doc > /tmp/Introduction_1.doc

沒有留言:

張貼留言