![](/img/trans.png)
[英]How do I use the datatable to retrieve data in my table from SQL Server in c #
[英]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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.