一尘不染

具有动态表名的C#查询

sql

我想建立一个查询,其中表名将是动态的,我将从另一个查询中获取它。这两个查询位于不同的数据上下文中。

代码

var tablename = (from tab in db.Tabs
                 where tab.id == tabid
                 select tab.name).FirstOrDefault();

var pid = (from p in tablename
           select p.id).FirstOrDefault();

阅读 275

收藏
2021-05-30

共1个答案

一尘不染

using(SqlConnection sqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
    SqlCommand com = new SqlCommand();
    SqlDataReader sqlReader;

    com.CommandText = "Select id from @tableName";
    com.CommandType = CommandType.Text;
    com.Parameters.Add(new SqlParameter("@tableName", tableName);

    com.Connection = sqlCon;
    sqlCon.Open();
    sqlReader = com.ExecuteReader();

    var dt = new DataTable();
    dt.Load(sqlReader); //Query output is in dt now
}
2021-05-30