我想建立一个查询,其中表名将是动态的,我将从另一个查询中获取它。这两个查询位于不同的数据上下文中。
代码
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();
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 }