我正在尝试使用DataTable来获取SQL Server数据库的模式. 但是,当尝试检测ForeignKeys时,约束集合仅带来UNIQUE约束. Private Sub ShowConstraints(ByVal tableName As String) Dim table As DataTable = New DataTable(table
但是,当尝试检测ForeignKeys时,约束集合仅带来UNIQUE约束.
Private Sub ShowConstraints(ByVal tableName As String) Dim table As DataTable = New DataTable(tableName) Using connection As SqlConnection = New SqlConnection(GetConnectionString) Dim adapter As SqlDataAdapter = New SqlDataAdapter("Select top 1 * from " + _ tableName, connection) connection.Open() adapter.FillSchema(table, SchemaType.Mapped) For Each c As Constraint In table.Constraints If TypeOf c Is ForeignKeyConstraint Then Dim fk As ForeignKeyConstraint = CType(c, ForeignKeyConstraint) Console.WriteLine("** FK ** relatedTable: {0}; RelatedColumns: {1}", _ fk.RelatedTable, fk.RelatedColumns) Else Console.WriteLine("** Whatever ** Name: {0}; Type: {1}", _ c.ConstraintName, c.GetType.ToString) End If Next End Using End Sub
我怎样才能获得ForeignKey约束?
那是出乎意料的.事实证明,毕竟FillSchema方法不会返回外键信息.我有一些看起来应该这样做的示例代码,但事实并非如此.
如果您真正想要的是以编程方式查询数据库中的所有FK,那么请从您的代码中尝试此系统存储过程.
msdb.dbo.sp_Help’tableName’
它返回一个数据集.第7个表具有表的所有约束,包括FK.