C# SMO- 检查目标服务器是否已经存在该表

3

我编写了一段使用SMO在两个远程服务器之间传输表格的C#代码,我想知道有没有办法检查目标服务器上是否已经存在具有完全相同模式、列名、数据类型、约束等的表。这样我就不必每次都删除现有表并创建新表了。


我在类似的问题中有一个更简单的方法:https://dev59.com/S0fSa4cB1Zd3GeqPAMsd#25273567 - user2188550
1个回答

2

尝试这段代码片段:

Server srv1 = new Server("<server_location>");
srv1.ConnectionContext.LoginSecure = false;
srv1.ConnectionContext.Login = "<username>";
srv1.ConnectionContext.Password = "<password>";
srv1.ConnectionContext.Connect();
Database sourceDb = srv1.Databases["<database_name>"];
Table sourceTbl = sourceDb.Tables["<table_name>"];

Server srv2 = new Server("<server_location>");
srv2.ConnectionContext.LoginSecure = false;
srv2.ConnectionContext.Login = "<username>";
srv2.ConnectionContext.Password = "<password>";
srv2.ConnectionContext.Connect();
Database destinationDb = srv1.Databases["<database name>"];
Table destinationTbl = sourceDb.Tables["<table_name>"];

var isMatched = CompareTables(sourceTbl, destinationTbl);    

比较方法:

bool CompareTables(Table source, Table destination)
{
    // Column count doesn't match
    if (!source.Columns.Count.Equals(destination.Columns.Count))
        return false;

    // Assuming the order of the Columns are same in both the Tables
    for (int i = 0; i < source.Columns.Count; i++)
        if (!source.Columns[i].Equals(destination.Columns[i]))
            return false;

    // Constraints count doesn't match
    if (!source.Checks.Count.Equals(destination.Checks.Count))
        return false;

    // Assuming the order of the Contraints are same in both the Tables
    for (int i = 0; i < source.Checks.Count; i++)
        if (!source.Checks[i].Equals(destination.Checks[i]))
            return false;

    return true;
}

这不只是检查是否存在相同名称和架构的表。我需要列、数据类型和约束。 - Ejaz
仍然不能帮助我解决约束问题。 - Ejaz
现在请检查我的答案。我已经在我的电脑上测试了这段代码。谢谢! - Furqan Safdar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接