Irakli Lekishvili
Irakli Lekishvili

Reputation: 34158

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;
        }
    }

alt text

Upvotes: 8

Views: 32906

Answers (3)

Dejan
Dejan

Reputation: 10313

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.

Upvotes: 0

Randy Minder
Randy Minder

Reputation: 48392

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.

Upvotes: 1

MarkXA
MarkXA

Reputation: 4384

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

Upvotes: 5

Related Questions