12

I have a csv that I need to parse into a gridview in vb.net. If I do SELECT *, I get the data without issue. However, I am in a situation where I need to reference the actual column names. And problem is, I have no control over the app that generates the csv, and they make the column names enclosed in square brackets.

How the heck can I do something like this:

Dim cmdSelect As New OleDbCommand(SELECT "[name], [height] FROM myTable")

so I get a return of data?

So, in an effort to be perfectly clear: I have an app that creates a csv with the column headers [name] and [height] in a table called myTable, and for the life of me I can't figure out how to return [name] and [height] specifically.

mrwienerdog
  • 815
  • 3
  • 18
  • 35

2 Answers2

17

If the column names have square brackets, then you can use double quotes to wrap around the column names. Below sample was tested in SQL Server.

Script:

CREATE TABLE dbo.myTable
(
        "[name]" varchar(max) not null
    ,   "[height]" int not null
);

Querying all the columns:

SELECT * FROM dbo.myTable

Querying only specific columns:

SELECT "[name]", "[height]" FROM dbo.myTable

VB.NET Code - Sample 1:

Dim query As String = String.Format("SELECT {0}{1}{0}, {0}{2}{0} FROM dbo.myTable", """", "[name]", "[height]")
Dim cmdSelect As New OleDbCommand(query)

VB.NET Code - Sample 2:

Dim query As String = String.Format("SELECT {0}[name]{0}, {0}[height]{0} FROM dbo.myTable", """")
Dim cmdSelect As New OleDbCommand(query)
1

I'm making the assumption that this is for SQL Server.

Objects that contain the ] character should be quoted using [].

For the following table :

CREATE TABLE [t]]] (
  [i]]d] int primary key,
  [da]]]ta] int
)

You can select from it using :

SELECT [da]]ta], [i]]d] FROM [t]]]

If you're looking for a way within T-SQL to quote object names, you can use QUOTENAME.

SELECT QUOTENAME('t]')

Within SQL Server, you can also use double-quotes to quote object names; however, there are two things you need to validate.

First you'll need to make sure that you enabled QUOTED_IDENTIFIER. Some drivers will be this for you automatically.

SET QUOTED_IDENTIFIER ON

The second think you'll need to do, is make sure that you escape any other double quotes in your object name. From T-SQL, QUOTENAME again comes to the rescue.

SELECT QUOTENAME('t"]')

"t""]"

In VB.Net you'd want to do something like :

dim queryStr As String = String.Format("SELECT ""{1}"" FROM dbo.myTable", String.Replace(col1, """", """"""))
Dennis
  • 164
  • 1
  • 3