簡體   English   中英

在C#中通過SMO發送時,是否可以將sql命令的結果輸出到文本文件?

[英]Is it possible to output the results of an sql command to a text file, when sent via SMO in C#?

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

任何幫助將非常感激!

我不知道您是否可以做完全相同的事情,但是假設腳本返回了一些數據,您可以執行腳本,讀取返回的數據並將其存儲到文件中,例如:

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();
                }
            }
        }
    }
}

發現我需要執行的SQL腳本基本上只將遇到的錯誤輸出到輸出文件中。 我能夠使用以下方法捕獲到該錯誤:

catch (Exception ex)
        {
            executedSuccessfully = false;

            SqlException sqlex = ex.InnerException as SqlException;

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

感謝您的幫助,但何! 我將來可能需要這個...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM