开发者

.NET, C#, SQL Server: Invalid object name with CREATE TABLE statement

I am trying to execute a CREATE TABLE which results in the following SQL exception:

Invalid object name 'UserLock'.

The statement looks like this:

USE [db]
GO

CREATE TABLE [db].[dbo].[UserLock] (
    [Login] [varchar](150) NOT NULL,
    [ExpirationDate] [datetime] NOT NULL,
    CONSTRAINT [PK_UserLock] PRIMARY KEY CLUSTERED
    ([Login] ASC)
    WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

The strange part is that I can run the query successfully inside the Microsoft SQL Management Studio with the same user but not within my .NET web application written in C#. I am not using any frameworks and I connect to the database with the provided classes out of System.Data.SqlClient. All other database queries work within the app. The database is Microsoft SQL Express 2005.

-- Edit ---

This is how my execution code looks like:

    string createString = "CREATE TABLE [" + catalog + "].[dbo].[UserLock]("
                        + "  [Login] [varchar](150) NOT NULL,"
                        + "  [ExpirationDate] [datetime] NO开发者_如何学运维T NULL,"
                        + "  CONSTRAINT [PK_UserLock] PRIMARY KEY CLUSTERED "
                        + "  ([Login] ASC)"
                        + "  WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]"
                        + ") ON [PRIMARY]";

    SqlCommand createCommand = connection.CreateCommand();
    createCommand.Connection = connection;
    createCommand.CommandText = createString;

    selectCommand.ExecuteNonQuery();

I catch the exception in another method. The SQL connection itself is beeing set up in antoher method, aswell. It's the standard SqlConnection connection = new SqlConnection(connectionString);


I am not sure how you are executing the above SQL but be aware that GO is not a SQL keyword, it is a command to tell SQL Management Studio to execute the current batch. I.E you cannot use GO outside of SQL management studio. Also i can't see how using GO would result in the above error. It might be best if you post the entire c# code that fails as the error might be elsewhere.


You can completely remove the following code:

USE [db] GO

You have fully qualified the create table statement with [Database].[Schema].[ObjectName] so it will create the table in the correct database and schema anyway.

Also, you shouldn't use GO in C# as it is specific to the SQL Mgmt Studio and is used to separate batches of SQL statements. If you really must use GO then take a look at Sql Server Management Object classes.

There is a nice blog post from Jon Galloway about it.


If you rename the table name? Does it work then, could be a protected word.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜