[英]Populate a List with all the table names which is having specified columns through sql in c#
我在sql server中有一个数据库,里面有几个表。
我需要填充一个包含来自数据库的表名列表的列表框,该数据库包含一个指定的列名,例如'special'。
我尝试过类似的东西。
using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); List<string> tables = new List<string>(); DataTable dt = connection.GetSchema("Tables"); foreach (DataRow row in dt.Rows) { string tablename = (string)row[2]; tables.Add(tablename); } listbox1.ItemsSource = tables; connection.Close(); }
但它显示数据库中存在的所有表。
但是我只想要那些在列表中有特定列的表...
请给我建议的方式... :)
您可以使用此linq查询(现已测试):
List<string> tNames= new List<string>(); // fill it with some table names
List<string> columnNames = new List<string>() { "special" };
// ...
IEnumerable<DataRow> tableRows = con.GetSchema("Tables").AsEnumerable()
.Where(r => tNames.Contains(r.Field<string>("TABLE_NAME"), StringComparer.OrdinalIgnoreCase));
foreach (DataRow tableRow in tableRows)
{
String database = tableRow.Field<String>("TABLE_CATALOG");
String schema = tableRow.Field<String>("TABLE_SCHEMA");
String tableName = tableRow.Field<String>("TABLE_NAME");
String tableType = tableRow.Field<String>("TABLE_TYPE");
IEnumerable<DataRow> columns = con.GetSchema("Columns", new[] { database, null, tableName }).AsEnumerable()
.Where(r => columnNames.Contains(r.Field<string>("COLUMN_NAME"), StringComparer.OrdinalIgnoreCase));
if (columns.Any())
{
tables.Add(tableName);
}
}
恕我直言,您应该只查询INFORMATION_SCHEMA.COLUMNS表,而不是尝试过滤返回的架构。 首先检索漏洞模式以丢弃大部分数据是完全无效的。
SELECT c.TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.COLUMN_NAME = 'YourLovelyColumnName'
假设您正在使用SQL Server:
IF COL_LENGTH('table_name','column_name') IS NOT NULL
BEGIN
/*Column exists */
END
查看更多:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.