【问题标题】:Is it possible to output the results of an sql command to a text file, when sent via SMO in C#?在 C# 中通过 SMO 发送时,是否可以将 sql 命令的结果输出到文本文件?
【发布时间】:2010-05-25 11:05:12
【问题描述】:

我在 C# 中使用 SMO 来运行 SQL 脚本。我需要将文件的结果输出到文本文件中。

当使用命令行运行查询时,我可以使用“-o [输出文件]”参数获得所需的结果。有没有办法使用 SMO 对象执行相同的操作?

目前我的代码只是将一个 sql 脚本发送到服务器:

// Read the sql file
string script = sqlFile.OpenText().ReadToEnd();

// Create a new sql connection, and parse this into a server connection.
SqlConnection sqlConnection = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(sqlConnection));

// Run the sql command.
server.ConnectionContext.ExecuteNonQuery(script);

任何帮助将不胜感激!

【问题讨论】:

    标签: c# sql smo


    【解决方案1】:

    我不知道你是否可以做完全相同的事情,但假设脚本返回一些数据,你可以执行脚本,读取返回的数据并将其存储到文件中,例如:

    using (StreamWriter sw = new StreamWriter("output.txt"))
    {
        using(SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using(SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = script;
                using(SqlDataReader rdr = cmd.ExecuteReader())
                {
                    while(rdr.Read())
                    {
                        sw.WriteLine(rdr.Item("colName").ToString();
                    }
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      发现我需要执行的SQL脚本基本上只将遇到的错误输出到输出文件中。我能够使用:

      catch (Exception ex)
              {
                  executedSuccessfully = false;
      
                  SqlException sqlex = ex.InnerException as SqlException;
      
                  if (sqlex != null)
                  {
                      exceptionText = sqlex.Message;
                  }
              }
      

      感谢您的帮助!我将来可能需要这个...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 2010-12-09
        • 2014-12-01
        • 2020-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多