0

I am trying to execute an SQL query at runtime:

        SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;
        cmd.CommandText = "SELECT * FROM dbo.Books_in_Storage WHERE author = 'myself'";
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = connection;
        connection.Open();
        reader = cmd.ExecuteReader();
        connection.Close();

Execution reaches reader = cmd.ExecuteReader(); and gives me the error:

Invalid object name dbo.Books in Storage.

If I look at my SQL Server Object Explorer, I can see that dbo.Books in Storage is present: enter image description here

Why is this happening?

9
  • 3
    Books in Storage and Books_in_Storage are not the same. Preferably, rename the table not to use spaces. Commented Dec 20, 2017 at 16:10
  • 1
    This is just one of the roughly 3,980,437 reasons not to use underscore or (especially) spaces in table and object names. Commented Dec 20, 2017 at 16:11
  • [dbo.Books_in_Storage] ? - but also avoid underscores Commented Dec 20, 2017 at 16:12
  • Also, "in storage" seems a red flag to me. They are probably just "Books" with perhaps a field (or related field or calculation) to indicate whether or not they are in storage. Commented Dec 20, 2017 at 16:15
  • It seems that you have created a database with AttachDbFileName but now you are not using anymore that property in your connection string and you don't specify any database to connect to. So your query works against the master database where there is no table with that name. (Of course the advices to not have tables with spaces are absolutely right) Commented Dec 20, 2017 at 16:23

1 Answer 1

1

In SQL Server, you can query a table with spaces using the [] as shown below, however, it is not normal to include spaces when choosing your database table names.

SELECT * FROM [table name]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.