简体   繁体   中英

Creating new sql server table with c#

I have this code to create new sql table when i execute this its shows me this error which is on screenshot. In my db there ise not such table. it shows this error any name of table. can anyone help me?

public void Create(string TName, string ConString)
    {
        try
        {
            using (SqlCommand cmd = new SqlCommand("CREATE TABLE [dbo].['" + TName + "']("
                            + "[ID] [int] IDENTITY(1,1) NOT NULL,"
                            + "[DateTime] [date] NOT NULL,"
                            + "[BarCode] [nvarchar](max) NOT NULL,"
                            + "[ArtNumber] [nvarchar](max) NOT NULL,"
                            + "[ProductName] [nvarchar](50) NOT NULL,"
                            + "[Quantity] [int] NOT NULL,"
                            + "[SelfPrice] [decimal](18, 2) NOT NULL,"
                            + "[Price] [decimal](18, 2) NOT NULL,"
                            + "[Disccount] [int] NULL,"
                            + "[Comment] [nvarchar](max) NULL,"
                            + "CONSTRAINT ['" + TName + "'] PRIMARY KEY CLUSTERED "
                            + "("
                            + "[ID] ASC"
                            + ")WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]"
                            + ") ON [PRIMARY]", new SqlConnection(ConString)))
            {
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();
            }
        }
        catch (Exception)
        {

            throw;
        }
    }

替代文字

You're using the same name for your table and its primary key. Try instead "CONSTRAINT ['pk_" + TName + "'] PRIMARY KEY CLUSTERED " .

The error message doesn't seem to be related to the name of the table. It seems related to the name of the constraint. It looks like you are naming a constraint 'beso' and another object by that name already exists in your DB.

Instead of fighting with SQL syntax, you could also use Mig# like this:

        var schema = new DbSchema(ConnectionString, DbPlatform.SqlServer2014);
        schema.Alter(db => db.CreateTable(TName)
           .WithPrimaryKeyColumn("Id", DbType.Int32).AsIdentity()
           .WithNotNullableColumn("DateTime", DbType.Date)
           ...);

The only down-side of this approach being that Mig# is not suitable to use very SQL Server specific features as it supports many platforms in a portable way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM