从SQL Server varbinary列临时检索数据

Dan*_*nov 6 sql-server varbinary

我想从varbinary(max)SQL Server数据库中的列中检索一些二进制数据以进行调试.

将此数据放入本地二进制文件的最简单方法是什么,最好不必编写丢弃的控制台应用程序?

我已经尝试使用SQL Server Management Studio(带有"results to file"选项)但是这会将十六进制编码的二进制字符串输出到文件,而不是原始二进制数据.

Dan*_*haw 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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

此代码已在SQL Server与Reporting Services的默认安装中使用Users.Sid​​列(varbinary类型)进行了测试.


Mah*_*vcs 3

我用命令找到了这个解决方案bcp(从命令提示符运行):

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.)
Run Code Online (Sandbox Code Playgroud)

我使用 -T 选项来使用 Windows 身份验证来连接到数据库。如果您使用密码身份验证,则需要使用 -U 和 -P 开关来指定用户名和密码。

但我也喜欢Robb Sadler 的回答中的LinqPad建议,并且在某种程度上更喜欢它。