簡體   English   中英

在SQL Server中檢索表的DataTable信息

[英]Retrieve DataTable info for a table in SQL Server

我需要獲取列名稱,主鍵,外鍵和其他架構信息。 DataTable類似乎包含所有這些。

以下是到目前為止的當前代碼。 有了它,我可以檢索除外之外的所有信息。 我希望它們在DataTable.Constraints定義,但DataTable.Constraints並非如此。 這是我當前的代碼:

    private static DataTable LoadSchemaInfo(string tableName, SqlConnection connection)
    {
        string cmdText = "SELECT * FROM [" + tableName + "] WHERE 1 = 0";

        // Create a SqlDataAdapter to get the results as DataTable
        var sqlDataAdapter = new SqlDataAdapter(cmdText, connection);

        // Create a new DataTable
        var dataTable = new DataTable(tableName);

        // Fill the DataTable with the result of the SQL statement
        sqlDataAdapter.FillSchema(dataTable, SchemaType.Source);

        return dataTable;
    }

知道如何檢索所有信息或如何獲取FK(最好不使用純SQL語法,因為這樣我將缺少一些編譯時檢查)嗎?

使用SMO,您可以執行此操作...

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.Agent;


// Add references: (in c:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\)
// Microsoft SqlServer.ConnectionInfo
// Microsoft SqlServer.Management.Sdk.Sfc
// Microsoft SqlServer.Smo

namespace SMO
{
    class Program
    {
        static Database db;

        static void Main(string[] args)
        {
            Microsoft.SqlServer.Management.Smo.Server server;

            SqlConnection sqlConnection = new SqlConnection(@"Integrated Security=SSPI; Data Source=LOCAL");
            //build a "serverConnection" with the information of the "sqlConnection"
            Microsoft.SqlServer.Management.Common.ServerConnection serverConnection =
              new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);

            //The "serverConnection is used in the ctor of the Server.
            server = new Server(serverConnection);

            db = server.Databases["TestDB"];

            Table tbl;
            tbl = db.Tables["Sales"];
            foreach (ForeignKey fk in tbl.ForeignKeys)
            {
                Console.WriteLine("Foreign key {0} references table {1} and key {2}", fk.Name, fk.ReferencedTable, fk.ReferencedKey);
            } 
        }
    }
}

您始終可以使用簡單的ADO.NET查詢來檢查數據庫中的sys目錄視圖-諸如:

  • sys.columns包含有關您的列的信息
  • sys.foreign_keys ,用於存儲有關外鍵的信息
  • 表的sys.tables

等。 只需SELECT (list of fields) FROM sys.foreign_keys執行SELECT (list of fields) FROM sys.foreign_keys ,看看會得到什么!

請參閱:聯機叢書查詢SQL Server系統目錄以獲取更多詳細信息。

如果您正在尋找數據庫架構的約束,那么ADO.net DataTable並不是最佳選擇。 您可能會發現使用SMO是更合適的選擇。

您可以使用SqlConnection來獲取信息。

string connectionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();

    DataTable dtAllForeignKeys = conn.GetSchema("ForeignKeys");

    string[] restrictionValues = { "Northwind", "dbo", "Orders" };
    DataTable dtForeignKeysForJustTheOrderTable = conn.GetSchema("ForeignKeys", restrictionValues);
    conn.Close();
}

DataTable對象與數據庫表不同。 由於您創建它們的方式,它們恰好具有相同的結構。 例如,您可能有一個包含多個數據庫表之間聯接結果的DataTable。 一個DataTable可以具有另一個DataTable的外鍵,但不能具有數據庫表的外鍵。

要獲取有關數據庫中外鍵的信息,您需要讀取表的元數據(當您調用SELECT時,您只獲得查詢的元數據,這就是為什么您不了解鍵的原因)。
您可以直接從信息架構視圖中查詢此信息,也可以讓SMO類為您執行此操作。 在后一種情況下,您從Server對象開始,然后獲取Database,Tables等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM