简体   繁体   English

如何将两个SQL Server表的比较保存到Excel文件?

[英]How to save comparison of two SQL Server tables to Excel file?

Well my question is related to Windows Forms, SQL Server and Excel. 好吧,我的问题与Windows窗体,SQL Server和Excel有关。

I am developing an app to compare data in two tables in SQL Server, and get the results. 我正在开发一个应用程序,以比较SQL Server中两个表中的数据,并获取结果。 The part up to inserting data into SQL Server tables and comparing tables is working fine, now I want to save that result of the comparison into an Excel file. 将数据插入SQL Server表和比较表的部分工作正常,现在我想将比较结果保存到Excel文件中。

I tried many methods but have failed so far :) I am giving my function to perform SQL compare option and help and to save that result into Excel. 我尝试了许多方法,但到目前为止都失败了:)我正在给我的函数执行SQL比较选项和帮助,并将结果保存到Excel中。

Thanks. 谢谢。

private void button2_Click(object sender, EventArgs e)
{
        if(checkBox1.Checked)
        {
            SqlConnection sqlConnection1 = new SqlConnection(MyConString);
            SqlCommand cmd = new SqlCommand();
            SqlDataReader reader;

            cmd.CommandText = "select Table1.Column from Table1 where Table1.Column1 not in (select Table2.Column2 from Table2 where Table2.Column2 = Table1.Column1)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = sqlConnection1;

            sqlConnection1.Open();

            reader = cmd.ExecuteReader();
        }
}

I want to save the result of this query to an Excel file 我想将此查询的结果保存到Excel文件中

You can save the resault to a .CSV file like follow: 您可以将重新保存到.CSV文件,如下所示:

  private void button2_Click(object sender, EventArgs e)
    {
            if(checkBox1.Checked)
            {
                SqlConnection sqlConnection1 = new SqlConnection(MyConString);
                SqlCommand cmd = new SqlCommand();
                SqlDataReader reader;

                cmd.CommandText = "INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=D:\;HDR=YES;FMT=Delimited','SELECT * FROM [FileName.csv]') select Table1.Column from Table1 where Table1.Column1 not in (select Table2.Column2 from Table2 where Table2.Column2 = Table1.Column1)";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = sqlConnection1;

                sqlConnection1.Open();

                reader = cmd.ExecuteReader();
            }
    }

If you need to do that with SSMS you can use Query toolbar ,just click on results to file and excute your query. 如果需要使用SSMS进行操作,则可以使用Query toolbar ,只需单击results to file并执行查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM