【问题标题】:How to access another command within a sql command in c#如何在c#中访问sql命令中的另一个命令
【发布时间】:2019-01-30 07:53:31
【问题描述】:

我正在创建一个迁移应用程序来将数据从一个应用程序迁移到另一个应用程序。

using (var conn = new System.Data.SqlClient.SqlConnection(""))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "SELECT * from Client";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                Client client = new Client();
                client.Active = reader["ActiveStatus"] == DBNull.Value ? false: Convert.ToBoolean(reader["ActiveStatus"]);
                client.Country = reader["Country"] == DBNull.Value ? 1 : Convert.ToInt32(reader["Country"]);
                client.Info = reader["Information"] == DBNull.Value ? "" : (string)reader["Information"];
            }
        }
    }
}

在上面,我需要使用Id 从另一个表中获取client.ProductId。如何在上面创建另一个查询来获取数据?我应该添加一个新命令吗?

【问题讨论】:

  • Client 表和“另一个”表之间的关系是什么?为什么不使用Joins 一次获取整个内容,而不是反复访问数据库?
  • 请添加两个 SQL 表以便我们为您提供帮助
  • 假设您想要执行两个单独的调用,您可以在一个命令的范围内执行两个选择操作,并使用 SqlDataAdapter 返回两个表的 DataSet。
  • 您可以创建一个包含调用单个 SQL 值 scalar 的函数的类,然后通过代码 public class Class1 { private SqlConnection con = new SqlConnection("myConnectionString"); private SqlCommand cmd = new SqlCommand(); private object obj; public object GetCell(string strsql) { cmd = new SqlCommand(strsql, con); if (con.State == ConnectionState.Open) con.Close(); con.Open(); obj = cmd.ExecuteScalar; con.Close(); return obj; } } 调用它

标签: c# sql sql-server


【解决方案1】:

在两个表之间使用 JOIN 而不是多个 sql 命令。 JOIN 会更快更容易。最好用这个。 For Reference

 cmd.CommandText = "SELECT Cl.ProductId,
                           Pr.ProductId,
                           Cl.ActiveStatus,
                           Cl.Country,
                           Cl.Information
                   from Client cl 
                   [INNER/LEFT/RIGHT] JOIN Product Pr 
                   on Cl.ProductId = Pr.ProductId";

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2011-06-24
    • 1970-01-01
    相关资源
    最近更新 更多