我的数据库中有一个外键,如:
ViewPager
所以写了一个小的c#程序来从我的数据库中获取CONSTRAINT [FK_Table1_Table2] FOREIGN KEY (Id) REFERENCES [Table2]([Id])
:
ForeignKeys
这将返回外键在using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString))
{
connection.Open();
DataTable getSchema = connection.GetSchema("Tables");
foreach (DataRow tableRow in getSchema.Rows)
{
String tableName = tableRow.Field<String>("TABLE_NAME");
DataTable fKeys = connection.GetSchema("ForeignKeys", new[] { database, "dbo", tableName });
foreach (DataRow keys in fKeys.Rows)
{
String tName = key.Field<String>("table_name");
}
}
}
上的Table
的名称,但我无法获得该外键引用(Table1)
的其他表的其他名称。
是否可以使用c#?
获取外键约束中另一个表的名称答案(由于标记为重复而在此处发布)
(Table2)
然后,您可以使用以下内容对表格进行过滤:
using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString))
{
connection.Open();
DataTable foreignKeys = new DataTable();
using (SqlCommand command = new SqlCommand("SELECT OBJECT_NAME(f.parent_object_id) ConsTable, OBJECT_NAME(f.referenced_object_id) refTable, COL_NAME(fc.parent_object_id, fc.parent_column_id) ColName FROM sys.foreign_keys AS f INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id INNER JOIN sys.tables t ON t.OBJECT_ID = fc.referenced_object_id order by ConsTable",connection))
{
using (SqlDataAdapter dataAdaptor = new SqlDataAdapter(command))
{
dataAdaptor.Fill(foreignKeys);
}
}
}