Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query a table that has spaces in its name

I have a situation, I have a Access table named Gas Flow Rates that I want to add records. When I try to run my insert query for a similar table Common Station, I get the following error:

"error hy000: syntax error, in query incomplete query clause"

Code is:

using System;
using System.Data.Odbc;

class MainClass
{
static void Main(string[] args)
{
    string connectionString = "Dsn=Gas_meter";
    string sqlins = "";
    OdbcConnection conn = new OdbcConnection(connectionString);

    OdbcCommand cmdnon = new OdbcCommand(sqlins, conn);
    conn.Open();

    try
    {
       cmdnon.CommandText = "INSERT INTO 'Common station' ( S1Flow, S2Flow, S3Flow, S4Flow) VALUES (9999,999, 999, 999)";
        //Once the above line works replace it with cmdnon.CommandText= "INSERT INTO Gas Flow Rates ( S1Flow, S2Flow, S3Flow, S4Flow) VALUES (9999,999, 999, 999)"
        int rowsAffected = cmdnon.ExecuteNonQuery();
        Console.WriteLine(rowsAffected);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        conn.Close();
    }
}
}

How do I overcome that error?

like image 740
LaDante Riley Avatar asked Jun 27 '11 20:06

LaDante Riley


People also ask

How do you query column names with spaces?

To select a column name with spaces, use the back tick symbol with column name. The symbol is ( ` `). Back tick is displayed in the keyboard below the tilde operator ( ~).

How does SQL handle spaces in names?

Do not use spaces in your table names either. While most database systems can handle names that include spaces, systems such as SQL Server require you to add brackets around the name when referencing it (like [table name] for example) which goes against the rule of keeping things as short and simple as possible.

How do you use table names with spaces in SQL?

Space in the database object name Incorrect syntax near the keyword 'Table'. To fix this error, we can specify the table name in the Square bracket. Alternatively, you can specify the table name in between double-quotes (“).

Can SQL table names have spaces?

Table names can contain any valid characters (for example, spaces).


3 Answers

Surround the spaced out item with square brackets:

[Common station]

Then slap the guy who designed the database.

like image 146
Gregory A Beamer Avatar answered Sep 22 '22 17:09

Gregory A Beamer


SELECT * FROM [My Crazy Table With Spaces and Other Chars!]

Use brackets to "quote" table and field names.

like image 23
Mike Caron Avatar answered Sep 20 '22 17:09

Mike Caron


  cmdnon.CommandText = "INSERT INTO '[Common station]' ( S1Flow, S2Flow, S3Flow, S4Flow) VALUES (9999,999, 999, 999)";
    //Once the above line works replace it with cmdnon.CommandText= "INSERT INTO Gas Flow Rates ( S1Flow, S2Flow, S3Flow, S4Flow) VALUES (9999,999, 999, 999)"
like image 26
ChrisBint Avatar answered Sep 19 '22 17:09

ChrisBint