问题
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