Way*_*fer 7 sql-server powershell c# sql-server-2012 smo
我正在尝试读取 winforms C# 应用程序中表和列的扩展属性。我正在使用 SQL Server SMO 来执行此操作。当我执行应用程序时,它看不到扩展属性,但是当我使用 PowerShell 读取扩展属性时,它确实看到了扩展属性。
C# 代码:
var x = col.ExtendedProperties.Count;
var NPI = col.ExtendedProperties["NPI"].Value;
bool npi = bool.Parse(NPI.ToString());
Run Code Online (Sandbox Code Playgroud)
PowerShell 代码:
Add-Type -AssemblyName "Microsoft.SqlServer.Smo, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $env:COMPUTERNAME
$server.Databases["<db name>"].Tables["<table name>"].Columns["<column name>"].ExtendedProperties | Select Name, Value, State
Run Code Online (Sandbox Code Playgroud)
我已经检查过,Visual Studio 和 PowerShell 都使用相同版本的 SMO (11.0.0.0)。当我执行 C# 代码时 col.ExtendedProperties.Count = 0,但是当我执行 PowerShell 代码时,我得到:
Name Value State
---- ----- -----
NPI False Existing
Run Code Online (Sandbox Code Playgroud)
有没有人对为什么会发生这种情况有任何想法?
在 C# 代码中,我使用以下方法在表上打开了一个 DataReader:
sourceServer.ConnectionContext.ExecuteReader(<select command>)
Run Code Online (Sandbox Code Playgroud)
从表中检索数据。然后我使用 DataReader 进入一个 while 循环,在那个 while 循环中我有:
foreach (Column col in sourceTable.Columns)
{
StringBuilder cleanData = CleanseColumn(col, dr[col.Name].ToString());
sbvalues.Append("'" + cleanData + "', ");
}
Run Code Online (Sandbox Code Playgroud)
当我单步执行 时foreach
,sourceTable
变量具有其扩展属性,但col
列变量没有。
您还没有显示实例化对象的代码col
,我们可以看看该代码吗?
使用类似 datareader 的GetSchemaTable()
方法实际上不会返回实际的(SQL SMO)表对象,它会返回一个具有许多有用的列属性的新表,但(据我所知)不包含扩展属性。
看看 Christopher Klein 在 StackOverflow 上的回答。如果我没看错的话,应该会返回一个实际的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"];
//warning, not tested, your code goes here
foreach (Column col in tbl.Columns)
{
var x = col.ExtendedProperties.Count;
var NPI = col.ExtendedProperties["NPI"].Value;
bool npi = bool.Parse(NPI.ToString());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,只需坚持使用您的工作 PowerShell 版本,或者诉诸此相关答案中的其他想法之一。
归档时间: |
|
查看次数: |
1540 次 |
最近记录: |