在Visual Studio 2019 c-sharp中检索SQL Server 2019表列列表的ExecuteSca



我在SQL Server数据库中有一个表,结构如下:

CREATE TABLE [file].[NumeTestINV](
[Category] [nvarchar](255) NULL,
[Class] [nvarchar](255) NULL,
[Company] [nvarchar](255) NULL,
[Division] [nvarchar](255) NULL,
[Jan] [float] NULL,
[Feb] [float] NULL,
[Mar] [float] NULL,
[Apr] [float] NULL,
[May] [float] NULL,
[Jun] [float] NULL,
[Jul] [float] NULL,
[Aug] [float] NULL,
[Sep] [float] NULL,
[Oct] [float] NULL,
[Nov] [float] NULL,
[Dec] [float] NULL
) ON [PRIMARY]

我试图在Visual Studio 2019 SSIS脚本任务中通过c#代码检索其列列表。我有以下代码片段:

//Get Matching Column List from SQL Server
string SQLColumnList = "";
SqlCommand cmd = myADONETConnection.CreateCommand();
cmd.CommandText = SQLQueryToGetMatchingColumn;
SQLColumnList = (string)cmd.ExecuteScalar();
MessageBox.Show(" Matching Columns: " + SQLColumnList);

然而,问题是列列表在ASCII中被错误地排序输出。我不知道为什么我的SQLColumnList没有出现正确的SQL表列顺序,因为它是物理上的,而是出现如下?

"[Apr],[Aug],[Category],[Class],[Company],[Dec],[Division],[Feb],[Jan],[Jul],[Jun],[Mar],[May],[Nov],[Oct],[Sep]"

我期待下面的输出:

"[Category],[Class],[Company],[Division],[Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec]"

下面是sqlquerytotmatchingcolumn的代码,我的源文件是一个Excel文件,具有与我的物理SQL表相同的列列表顺序:

SQLQueryToGetMatchingColumn = "select STUFF((Select  ',['+Column_Name+']' from Information_schema.Columns where Table_Name='" +
TableName + "' and Table_SChema='" + SchemaName + "'" +
"and Column_Name in (" + @ExcelHeaderColumn + ") for xml path('')),1,1,'') AS ColumnList";

sqlquerytotmatchingcolumn的输出如下:

"select STUFF((Select  ',['+Column_Name+']' from Information_schema.Columns where Table_Name='NumeTestINV' and Table_SChema='file'and Column_Name in ('Category','Class','Company','Division','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') for xml path('')),1,1,'') AS ColumnList"

CommandText输出如下:

"select STUFF((Select  ',['+Column_Name+']' from Information_schema.Columns where Table_Name='NumeTestINV' and Table_SChema='file'and Column_Name in ('Category','Class','Company','Division','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') for xml path('')),1,1,'') AS ColumnList"

我希望这是我的代码片段中的一个小代码更改,并且我不必完全改变我检索SQL列列表的方法。

如果您希望列按顺序排列,请尝试这样做:

select string_agg( quotename(name), ', ') within group (order by columnproperty(c.object_id, c.name, 'ordinal') ) columnList
from sys.columns c
where c.object_id = object_id('[file].[NumeTestINV]')

select string_agg( quotename(column_name), ', ') within group (order by ordinal_position) columnList
from information_schema.COLUMNS
where TABLE_SCHEMA = 'file'
and TABLE_NAME = 'NumeTestINV'

或使用旧的XML格式

select STUFF((Select  ','+ quotename(Column_Name) from Information_schema.Columns where Table_Name='NumeTestINV' and Table_SChema='file'and Column_Name in ('Category','Class','Company','Division','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') order by ordinal_position for xml path('')),1,1,'') AS ColumnList

最新更新