gpt4 book ai didi

c# - 检索 SQL Server 中表的 DataTable 信息

转载 作者:行者123 更新时间:2023-12-03 22:56:24 25 4
gpt4 key购买 nike

我需要获取列名、主键、外键和其他架构信息。 DataTable 类似乎包含所有这些。

下面是我到目前为止得到的当前代码。有了它,我可以检索除外键之外的所有信息。我希望它们在 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);
}
}
}
}

关于c# - 检索 SQL Server 中表的 DataTable 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3942287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com