我正在编写一个c#单元测试,用于针对目标数据库,总是SQL 2008以及数据映射到的类验证ORM类的字符串属性。SQL 2008 - INFORMATION_SCHEMA视图中的外键约束
检查指定的外键是在DB有效很简单:
static private bool ConstraintExsits(string table, string column, ConstraintType constraintType)
{
string constraintTypeWhereClause;
switch (constraintType)
{
case ConstraintType.PrimaryKey:
constraintTypeWhereClause = "PRIMARY KEY";
break;
case ConstraintType.ForeignKey:
constraintTypeWhereClause = "FOREIGN KEY";
break;
default:
throw new ArgumentOutOfRangeException("constraintType");
}
var cmd = new SqlCommand(
@"SELECT a.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS a
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE b on a.CONSTRAINT_NAME = b.CONSTRAINT_NAME
WHERE a.TABLE_NAME = @table AND b.COLUMN_NAME = @column AND a.CONSTRAINT_TYPE = '" + constraintTypeWhereClause + "'",
Connection);
cmd.Parameters.AddWithValue("@table", table.Trim('[').Trim(']'));
cmd.Parameters.AddWithValue("@column", column.Trim('[').Trim(']'));
return !string.IsNullOrEmpty((string)cmd.ExecuteScalar());
}
现在采取以下外键关系:
我的问题:我如何查询'Primary/Unique Key Base Table'和'Primary/Unique Key Columns'边的关系?我无法在INFORMATION_SCHEMA视图中看到这些引用。
感谢 Ĵ
太棒了!谢谢。 – 2012-10-25 21:12:30