【问题标题】:How use wild card in table name for GetSchema method?GetSchema 方法如何在表名中使用通配符?
【发布时间】:2016-01-24 16:08:13
【问题描述】:

我想使用 oledb GetSchema 方法查询数据库中名称以特定字符串开头的所有现有表。 换句话说,我正在寻找以下 sql 查询的等效项:

SELECT * FROM information_schema.tables WHERE table_name  LIKE 'customer%'

类似:

String[] tableRestrictions = new String[4];
tableRestrictions[2] = "%customer";
DataTable customerTables = conn.GetSchema("Tables", tableRestrictions );

【问题讨论】:

  • 您可以使用该查询,但您需要像执行任何其他 SQL 查询一样执行它(即使用IDbCommand)。不知道为什么要使用GetSchema()
  • 或者您可以自己循环浏览架构。字段不应该太多。
  • @CG:当我使用该查询时,它会返回空数据表。
  • @LarsTech:实际上表太多了,我想看看数据库中存在哪些表。实际上,由于某些原因,表名是动态的,我应该先找到表名才能查询它。
  • 然后你只需在传递表名等的地方创建一个函数。

标签: c# sql oledb


【解决方案1】:

在这种情况下,我要查询的表名是动态的。因此,我需要先获取整个表名。

似乎没有有效的方法来做到这一点,但使用迭代。 我得出的结论是,使用 Linq 提供了最简洁的解决方案(感谢 Tim's answer to a similar case):

// Get the tables using GetSchema:
dtbTables = dbConnection.GetSchema("tables");

// use linq to get the table whose name matches the criteria:
DataRow recSpecificTable = dbConnection.GetSchema("Tables").AsEnumerable()
                .Where(r => r.Field<string>("TABLE_NAME")
                .StartsWith("customer")).FirstOrDefault();

// Now the table name I am looking for:
tableName = Convert.ToString(recSpecificTable["TABLE_NAME"]).Trim();

【讨论】:

    猜你喜欢
    • 2012-06-25
    • 1970-01-01
    • 2011-09-01
    • 2021-11-27
    • 2020-09-25
    • 2023-04-07
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多