如何在C#中将存储过程结果用作子查询

时间:2019-10-30 01:50:44

标签: c# sql

我有一个执行SQL查询的C#代码。 SQL查询的输入来自存储过程的结果。该存储过程返回一个表,该表有6列和25,000行。我想将此存储过程结果用作SQL查询的输入。我将存储过程的结果存储在DataSet中。看来这不是在查询中添加DataSet结果的正确方法。我需要专家的帮助

这就是我在做什么。

public static void ExecuteSQLQueryTest(string qryName, Boolean nestedQry, string spName)
{
    DataTable dtLocalResult = new DataTable();
    DataTable dtAzurelResult = new DataTable();
    DataTable dt = new DataTable();
    DataTable dt1 = new DataTable();
    List<string> lstring = new List<string>();
    aadSQLConnection.Open();
    //Connection to CPDashboard DB
    var cpdbconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["CATSQL"].ConnectionString);
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = cpdbconnection;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = spName;

        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            da.Fill(dt);
        }
    }

    string qryName = "Update A SET A.Environment = B.SC_MD_Environment, A.OSImage = B.SC_APMD_OSImage FROM" + dt + " A"
        + "INNER JOIN[CLOUD].cloudsql.caa.aa_AT_S B ON A.ServerName = B.SC_APMD_MachineName";

    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = aadSQLConnection;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = qryName;
        using (SqlDataAdapter daa = new SqlDataAdapter(cmd))
        {
            daa.Fill(dt1);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

访问cell value中的DataTable应该采用这种格式

dt[row index][col index]

而且,我们需要在您的TableFrom之间放置空格

string qryName = "Update A SET A.Environment = B.SC_MD_Environment, A.OSImage = B.SC_APMD_OSImage "
        + "FROM " + dt[0][0] + " A"
        + "INNER JOIN[CLOUD].cloudsql.caa.aa_AT_S B ON A.ServerName = B.SC_APMD_MachineName";

如果您尝试从存储过程输出中更新datatable。您需要改为对云表使用select查询,然后更新datatable

foreach(DataRow row in dt.Rows)
{
    string qryName = "select Environment from [CLOUD].cloudsql.caa.aa_AT_S B where A.ServerName = '"+row["ServerName"].ToString()+"'";

    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = aadSQLConnection;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = qryName;
        using (SqlDataAdapter daa = new SqlDataAdapter(cmd))
        {
            .....update your datable here
        }
    }
}