SQLDataReader 不显示字段名称中带有双冒号的列的值



当我在SQL Server上的SQL Server Management Studio中输入Select查询时,它可以正常工作:

SELECT [00:00] 
FROM MY_TABLE 
WHERE whatevercondition ...

列名称为"00:00" - 它有一个双冒号。当我尝试在 VB.net 函数中获取此列的值时,SqlDataReader ,结果总是一个错误:

列不存在

我试图将列名放在括号、引号的所有变体中,根本没有括号等。我仍然无法检索表中的值。

我的 VB.NET 代码:

Dim Counter_Adapter As New SqlDataAdapter
Dim Counter_Table As New DataTable
Dim Counter_Reader As SqlDataReader
Dim SQLTemp As String
Dim TheField as String
Dim result as String
TheField = "[00:00]"
SQLTemp = "SELECT " & TheField & " FROM MY_TABLE WHERE whatevercondition ..."
Data_CMD_Counter = New SqlCommand(SQLTemp, MyDatabaseConnection)
Counter_Adapter.SelectCommand = Core.Data_CMD_Counter
Counter_Adapter.Fill(Counter_Table)
Counter_Reader = Core.Data_CMD_Counter.ExecuteReader
If Counter_Reader.HasRows = True Then
    result = Counter_Table.Rows(0)(TheField).ToString() 'This line causes the error: Column "[00:00]" not included in the table.
Else
End If

如何正确引用/转义列名,以便它在SqlDataReader中工作?

这个:

TheField = "[00:00]"
SQLTemp = "SELECT " & TheField & " FROM MY_TABLE WHERE whatevercondition ..."

应该是

TheField = "00:00"
SQLTemp = "SELECT [" & TheField.Replace("]", "]]") & "] FROM MY_TABLE WHERE whatevercondition ..."

名称是 00:00 . 不[00:00]. 这是一个分隔标识符,[]仅存在于 TSQL 中,当名称不遵循常规标识符的规则时,使解析器能够告诉名称的开始和结束位置。

尝试使用列的序号索引,而不是列名。

像这样,在 SELECT 语句的第一列使用 0

result = Counter_Table.Rows(0)(0).ToString()

相关内容

  • 没有找到相关文章

最新更新