0

我在 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);

任何帮助将非常感激!

4

2 回答 2

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();
                }
            }
        }
    }
}
于 2010-05-25T11:31:25.563 回答
0

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

catch (Exception ex)
        {
            executedSuccessfully = false;

            SqlException sqlex = ex.InnerException as SqlException;

            if (sqlex != null)
            {
                exceptionText = sqlex.Message;
            }
        }

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

于 2010-05-25T16:02:17.653 回答