Click here to Skip to main content
15,906,766 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm using the following code to create a table within a database on SQL Server 2008 R2. The table doesn't show up in the "Data Connection" under the database/table in VS2013 or SQL Studio. However, the method DbTableExists says it does exist. I've tried with and without the [dbo].[table-name], doesn't make a difference.

I've tried refreshing, closing/restarting SQL Studio, and I still can't it to show up.

Any help is greatly appreciated.

Thanks,
Glenn

C#
if (!DbTableExists(connectionString, "[dbo].[Server]"))
{
    try
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string strCreateTable =
                @"CREATE TABLE [dbo].[Server] 
                (ServerName	    nvarchar(15) PRIMARY KEY,
                 LastUpdate         datetime,
                )";

            SqlCommand command = new SqlCommand(strCreateTable, connection);
            command.CommandType = CommandType.Text;
            connection.Open();
            command.ExecuteReader();
            connection.Close();
       }
   }
...

private static bool DbTableExists(string strConnection, string strTableNameAndSchema)
{
    using (SqlConnection connection = new SqlConnection(strConnection))
    {
        string strCheckTable = 
           String.Format("IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT                        'false'",
                      strTableNameAndSchema);

        SqlCommand command = new SqlCommand(strCheckTable, connection);
        command.CommandType = CommandType.Text;
        connection.Open();

        return Convert.ToBoolean(command.ExecuteScalar());
    }
}
Posted
Comments
PIEBALDconsult 20-Dec-13 23:34pm    
Did it wind up in the Master database?

<br />
            string strCreateTable =<br />
                @"CREATE TABLE [dbo].[Server] <br />
                (ServerName	    nvarchar(15) PRIMARY KEY,<br />
                 LastUpdate         datetime,<br />
                )";<br />

Try removing dbo and run the query again.
 
Share this answer
 
OK, all I can say is wow. I'm surprised there wasn't an exception thrown. The problem was I forgot to update the connection string after I created the database to include the database name. The tables were being created, probably under one of the System Database.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900