如何从Sql Server系统消息中获取返回值?

时间:2012-05-30 03:12:09

标签: c# sql sql-server smo

我正在尝试使用针对sql server Express的命令验证我刚刚在c#中执行的备份

 string _commandText =  string.Format("RESTORE VERIFYONLY FROM DISK = '{0}'", backupLocation);

 SqlDataReader _sqlDataReader = SqlHelper.ExecuteReader("BookssortedSQLDbConnection", CommandType.Text, _commandText);

如果我在SSMS中执行该命令,则返回“文件1上的备份集有效”。但是如何才能将此消息重新发送到我的代码中?

读者无法工作,因为没有返回任何行。

注意:我已经尝试过SMO.Restore对象来尝试验证它,但它不起作用,这就是我这样做的原因。

_restore.SqlVerify(srv, out _errorMessage); //returns false even though bakcup is fine
BTW - 接受建议,因为我不认为这是实现我想做的事情的理想方式

2 个答案:

答案 0 :(得分:14)

信息性消息(严重性小于10)和PRINT输出将返回给客户端,并由InfoMessage实例引发为SqlConnection个事件。每个事件都包含SqlError个对象的集合(这与SqlException.Errors中使用的类相同)。

这是一个完整的示例,显示连接状态更改,信息消息和异常。请注意,我使用ExecuteReader代替ExecuteNonQuery,但信息和异常结果相同。

namespace Test
{
    using System;
    using System.Data;
    using System.Data.SqlClient;

    public class Program
    {
        public static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Usage();
                return 1;
            }

            var conn = args[0];
            var sqlText = args[1];
            ShowSqlErrorsAndInfo(conn, sqlText);

            return 0;
        }

        private static void Usage()
        {
            Console.WriteLine("Usage: sqlServerConnectionString sqlCommand");
            Console.WriteLine("");
            Console.WriteLine("   example:  \"Data Source=.;Integrated Security=true\" \"DBCC CHECKDB\"");
        }

        public static void ShowSqlErrorsAndInfo(string connectionString, string query)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.StateChange += OnStateChange;
                connection.InfoMessage += OnInfoMessage;

                SqlCommand command = new SqlCommand(query, connection);
                try
                {
                    command.Connection.Open();
                    Console.WriteLine("Command execution starting.");
                    SqlDataReader dr = command.ExecuteReader();
                    if (dr.HasRows)
                    {
                        Console.WriteLine("Rows returned.");
                        while (dr.Read())
                        {
                            for (int idx = 0; idx < dr.FieldCount; idx++)
                            {
                                Console.Write("{0} ", dr[idx].ToString());
                            }

                            Console.WriteLine();
                        }
                    }

                    Console.WriteLine("Command execution complete.");
                }
                catch (SqlException ex)
                {
                    DisplaySqlErrors(ex);
                }
                finally
                {
                    command.Connection.Close();
                }
            }
        }

        private static void DisplaySqlErrors(SqlException exception)
        {
            foreach (SqlError err in exception.Errors)
            {
                Console.WriteLine("ERROR: {0}", err.Message);
            }
        }

        private static void OnInfoMessage(object sender, SqlInfoMessageEventArgs e)
        {
            foreach (SqlError info in e.Errors)
            {
                Console.WriteLine("INFO: {0}", info.Message);
            }
        }

        private static void OnStateChange(object sender, StateChangeEventArgs e)
        {
            Console.WriteLine("Connection state changed: {0} => {1}", e.OriginalState, e.CurrentState);
        }
    }
}

答案 1 :(得分:2)

很难将ssms消息检索到前端应用程序。但是,您可以将消息写入文本文件,然后从文件中读取数据。

declare @cmd varchar(1000)

SET @cmd = 'osql -S YourServer -E -d YourDatabase -q "RESTORE VERIFYONLY FROM   DISK=''c:\yourBackup.bkp''" -o c:\result.txt'

EXEC master.dbo.xp_cmdshell @cmd

您可以从应用程序执行上述sql语句,然后从result.txt文件中读取结果