查询数据库并输出结果以在C#

问题描述

我在C#中有一个查询,该查询正在我的服务器上执行。它返回一个列,但我想将列的结果生成并将它们生成为IN语句,以传递到另一台服务器上的另一个查询

这是代码,我只是不知道如何编写逻辑来输出每一行:

            System.Data.DataTable dtCups = new System.Data.DataTable();
            var dataSet = new DataSet();

            string connString = "Data Source=My Server;" + "Integrated Security=sspI;";

            sqlConnection Conn = new sqlConnection(connString);
            Conn.open();
            
            String qryCups = "select cups from table"; //returns 300 rows

            sqlDataAdapter adapter = new sqlDataAdapter(qryCups,Conn);
            adapter.Fill(dtCups);
            Conn.Close();
 
            foreach (DaTarow dr in dtCups.Rows)
            {
                string cups = dr.ItemArray[0].ToString();
                DaTarow[] MatchRecs = dtCups.Select("cups='" + dr.ItemArray[0] + "'");

            }

只是不确定要执行的操作,因为它遍历每个记录,但没有将先前的杯子值附加到下一个值,例如“ cup1”,“ cup2”等。

谢谢。

一个sql语句的代码

String qryFinal = "select cups from table_B where cups in '" + [the output of the data above] + "'";

然后我将结果插入到最终表中或放入Excel(我知道该怎么做);

解决方法

您应该阅读表并逐行创建两个列表。第一个将包含参数名称,第二个将包含参数本身以及数据表提取的值。 在循环退出时,您将构建一个查询文本,将IN语句中的参数名称结合在一起,然后将参数传递给SqlCommand本身。

List<string> pNames = new List<string>();
List<SqlParameter> prms = new List<SqlParameter>();
for (int x = 0; x < dtCups.Rows.Count; x++)
{
    // Create the parameters names list @0,@1,@2 etc..
    pNames.Add($"@{x}");

    // Create the parameters,note that I assume a string type parameter with a length of 255 characters max. Adjust if assumption is wrong
    SqlParameter p = new SqlParameter($"@{x}",SqlDbType.NVarChar,255);
    p.Value = dtCups.Rows[x][0].ToString();
    prms.Add(p);
}

.....

// Create the final sql command text from the parameters names
string qryFinal = "select cups from table_B where cups in(" + 
                  string.Join(",",pNames) + ")";
SqlCommand cmd = new SqlCommand(qryFinal,connection);

// Add the parameter list to the command collection and then execute
cmd.Parameters.AddRange(prms.ToArray());
SqlDataReader reader = cmd.ExecuteReader() 

// Or DataAdapter.Fill table
DataTable aTable = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
da1.Fille(aTable);