C# query with dynamic tablename

爷,独闯天下 提交于 2020-06-28 06:34:10

问题


I want to build a query where the tablename will be dynamic and I will get it from another query. The 2 queries are in different datacontexts.

CODE

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();

回答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
}



回答2:


Table names cannot be supplied as parameters, so you'll have to construct the SQL string manually in either a function or stored procedure before you can execute it.

    create PROC read_from_dynamic_table(@TableName NVARCHAR(50))
AS
BEGIN 
DECLARE @SQLSelectQuery NVARCHAR(MAX)=''
SET @SQLSelectQuery = 'SELECT * FROM ' + @TableName

  exec(@SQLSelectQuery)
END

Then you can call the proc to with table name as parameter




回答3:


To feed table name dynamically into the 2nd query, you can use stored procedure instead of LINQ.

When you got your stored procedure, you then call it by passing tablename (the result from your first query.

SP doc: https://docs.microsoft.com/en-us/sql/relational-databases/stored-procedures/create-a-stored-procedure

This is an rough example just to give you an idea:

  CREATE PROCEDURE InsertProc
   @tablename varchar(100)
  AS
  begin 
   select * from @tablename  
 end 


来源:https://stackoverflow.com/questions/46765395/c-sharp-query-with-dynamic-tablename

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!