gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:09:13 26 4
gpt4 key购买 nike

我已经编写了一个 C# 代码来使用 SMO 在两个远程服务器之间传输表,我想知道的是无论如何都可以检查目标服务器中是否已经存在具有确切模式、列名、数据类型的表,约束和一切。这样我就不必每次都删除现有表并创建新表。

最佳答案

试试这段代码片段:

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;
}

关于C# SMO-检查表是否已存在于目标服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13133607/

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