Export blob from remote sql server and save to file on disk where sql server is located [C#]

余生长醉 提交于 2019-12-11 17:27:10

问题


What i Need to do: im working on a backup and restore tool for my Company. Backup remote SQL databases is done without any Problems. But i have Problems while restoring them. I'm currently creating a temporary table on the remote SQL where the binary of the database is saved.

Now i Need to Export this binary field from a remote SQL Server to a file that Needs to be saved on remote disk too. This tool has the requirement to get started on local machine so there is no way of running it on remote Server.

Current code part:

using (SqlConnection conn = new SqlConnection(sqlConnectionString))
            {
                System.Data.SqlClient.SqlCommand commandAdd = new SqlCommand("CREATE TABLE dbo.tempTable (filename char(50), blob image);", conn);
                conn.Open();

                if (commandAdd.ExecuteNonQuery() != 0)
                {
                    byte[] fileBytes = System.IO.File.ReadAllBytes(fileSource);
                    System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("INSERT INTO dbo.tempTable (blob,filename) values (@blob,@name)", conn);
                    command.Parameters.AddWithValue("blob", fileBytes);
                    command.Parameters.AddWithValue("name", dbName);

                    if (command.ExecuteNonQuery() != 0)
                    {
                        // This is just for testing if i get binary back
                        // string SQL = "SELECT blob FROM dbo.tempTable";
                        // SqlCommand cmd = new SqlCommand(SQL, conn);
                        // byte[] byt = (byte[])cmd.ExecuteScalar();

                        // I think Problem is within this 2 lines..
                        Server server = new Server(new ServerConnection(conn));
                        server.ConnectionContext.ExecuteReader("'bcp.exe \"SELECT blob FROM dbo.tempTable\" queryout " + destinationSource + " -T -c'");

                        Restore restore = new Restore();
                        restore.Database = "_" + dbName;
                        restore.Action = RestoreActionType.Database;
                        restore.ReplaceDatabase = true;
                        restore.Devices.AddDevice(destinationSource, DeviceType.File);
                        restore.ReplaceDatabase = true;
                        restore.NoRecovery = false;
                        Server sqlServer = new Server(new ServerConnection(conn));
                        restore.SqlRestore(sqlServer);
                    }
                }

                SqlCommand commandDelete = new SqlCommand("DROP TABLE dbo.tempTable", conn);
                commandDelete.ExecuteNonQuery();
                conn.Close();
            }

Thanks


回答1:


OK, i try again. Look here: https://www.simple-talk.com/sql/t-sql-programming/the-tsql-of-text-files/

--then we execute the BCP to save the file
  SELECT  @Command = 'bcp "select BulkCol from ['
          + @MySpecialTempTable + ']'
          + '" queryout '
          + @Filename + ' '
         + CASE WHEN @Unicode=0 THEN '-c' ELSE '-w' END
          + ' -T -S' + @@servername
  EXECUTE @RESULT= MASTER..xp_cmdshell @command, NO_OUTPUT

You can call, from c# code, xp_cmdshell that execute the command (and save the file) on the server




回答2:


Can you use FILESTREAM on the remote server? You could save the Backup into a FILESTREAM column, which would save it to disk and you can configure FILESTREAM to make the stream available to other processes (in this case SQL Server itself).

If the FILESTREAM-column for example is named "Backup", you can get the corresponding path with Backup.PathName() and use this to issue a RESTORE command, which I think would be a pretty elegant solution to your problem (without using xp_cmdshell or similar nasty workarounds).

A simple example for such a "Filestream Backup Table" would be

CREATE TABLE MyBackup
(
  BackupName VARCHAR(100),                -- To identify the backup
  BackupContent VARBINARY(max) FILESTREAM -- To store the physical backup
);

You may get an error when trying to create such a table, depending on whether the FILESTREAM feature is enabled or disabled on the given server and database (it's disabled by default).



来源:https://stackoverflow.com/questions/21481221/export-blob-from-remote-sql-server-and-save-to-file-on-disk-where-sql-server-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!