2010-04-28 72 views
6

我想從SQL Server數據庫的varbinary(max)列中檢索一些二進制數據以用於調試目的。從SQL Server varbinary列中臨時刪除數據

將這些數據導入本地二進制文件最簡單的方法是什麼?最好不必編寫一個丟棄控制檯應用程序?

我試過使用SQL Server Management Studio(「結果到文件」選項),但是這會將十六進制編碼的二進制字符串輸出到文件而不是原始二進制數據。

+3

我不確定這是您尋找的內容,但您是否瞭解LINQPad?它基本上是一個應用程序,您可以在其中編寫「拋棄」C#應用程序。 – 2010-04-28 09:04:34

回答

3

我發現this solutionbcp命令(從命令提示符下運行):

c:\temp>bcp "select MYVARBINARYCOL from MYTABLE where id = 1234" queryout "c:\filename.pdf" -S MYSQLSERVER\MYINSTANCE -T 

Enter the file storage type of field filedata [varbinary(max)]: 
Enter prefix-length of field filedata [8]: 0 
Enter length of field filedata [0]: 
Enter field terminator [none]: 

Do you want to save this format information in a file? [Y/n] n 

Starting copy... 

1 rows copied. 
Network packet size (bytes): 4096 
Clock Time (ms.) Total : 15 Average : (66.67 rows per sec.) 

我用-t選項來使用Windows身份驗證連接到D B。如果您使用密碼身份驗證,則需要使用-U和-P開關指定用戶名和密碼。

但我也喜歡LinqPadRobb Sadler's answer建議,並以某種方式更喜歡它。

6

我想不出任何更簡單的方式來做到這一點比扔掉位C#...

static void Main(string[] args) 
    { 
     GetBinaryDataToFile("Server=localhost;Initial Catalog=ReportServer;Integrated Security=true", "D:\\temp.dat"); 
    } 

    public static void GetBinaryDataToFile(string connectionString, string path) 
    { 
     using (SqlConnection connection = new SqlConnection(connectionString)) 
     { 
      connection.Open(); 

      using (SqlCommand command = connection.CreateCommand()) 
      { 
       command.CommandText = "SELECT Sid FROM Users WHERE UserID = '62066184-8403-494E-A571-438ABF938A4F'"; 
       command.CommandType = CommandType.Text; 

       using (SqlDataReader dataReader = command.ExecuteReader()) 
       { 
        if (dataReader.Read()) 
        { 
         SqlBinary sqlBinary = dataReader.GetSqlBinary(0); 
         File.WriteAllBytes(path, sqlBinary.Value); 
        } 

        dataReader.Close(); 
       } 
      } 

      connection.Close(); 
     } 
    } 

此代碼已被使用Users.Sid​​列(這是VARBINARY類型的測試)在SQL Server與Reporting Services的默認安裝中。

4

我喜歡LinqPad的建議。我試了一下,並有一個查詢在10分鐘內將二進制文件吐出到文件中。沒有VS項目,沒有建立 - 現在腳本被保存了,我可以隨時把它拉起來。非常酷!

LinqPad腳本:

var g = from pd in Archives 
    where pd.ArchiveId == 123 
    select pd; 

var q = from p in printDocs 
where p.DocumentId == g.SingleOrDefault().DocumentId 
select p; 

File.WriteAllBytes("C:\\temp.pdf", q.SingleOrDefault().Pdf.ToArray()); 
+0

我不明白。這在LinqPad中如何工作? '檔案'在哪裏定義?你是否引用了一些定義了Linq-to-SQL/EntityFramework實體的外部庫? – 2011-06-07 14:40:27

+0

我附加到我的數據庫,LinqPad自動構建了Linq to Sql數據類。然後我可以訪問和使用它。這是什麼讓它變得酷的一部分。這是一個快速下載 - 我建議給它一個旋風。這是我寫的唯一代碼。 – 2011-06-10 14:09:25