0

SQLスクリプトを実行するためにC#でSMOを使用しています。ファイルの結果をテキストファイルに出力する必要があります。

コマンドラインを使用してクエリを実行する場合、「-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 に答える