简体   繁体   English

具有动态表名的C#查询

[英]C# query with dynamic tablename

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

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. 表名不能作为参数提供,因此必须先在函数或存储过程中手动构造SQL字符串,然后才能执行它。

    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 然后您可以使用表名作为参数调用proc到

To feed table name dynamically into the 2nd query, you can use stored procedure instead of LINQ. 要将表名动态输入第二个查询,可以使用存储过程代替LINQ。

When you got your stored procedure, you then call it by passing tablename (the result from your first query. 当您获得存储过程时,可以通过传递tablename (第一个查询的结果)来调用它。

SP doc: https://docs.microsoft.com/en-us/sql/relational-databases/stored-procedures/create-a-stored-procedure SP文档: https : //docs.microsoft.com/zh-cn/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 
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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM