我有这个代码来创建新的sql表 当我执行它时它显示我在屏幕截图上的这个错误。在我的数据库中没有这样的表。它显示此错误的任何名称的表。有谁可以帮助我?
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;
}
}
答案 0 :(得分:5)
您对表及其主键使用相同的名称。请改为"CONSTRAINT ['pk_" + TName + "'] PRIMARY KEY CLUSTERED "
。
答案 1 :(得分:1)
错误消息似乎与表的名称无关。它似乎与约束的名称有关。看起来您正在命名一个约束'beso',并且该名称中的另一个对象已存在于您的数据库中。
答案 2 :(得分:0)
您也可以使用Mig#来代替使用SQL语法:
var schema = new DbSchema(ConnectionString, DbPlatform.SqlServer2014);
schema.Alter(db => db.CreateTable(TName)
.WithPrimaryKeyColumn("Id", DbType.Int32).AsIdentity()
.WithNotNullableColumn("DateTime", DbType.Date)
...);
这种方法的唯一缺点是Mig#不适合使用非常特定于SQL Server的功能,因为它以便携方式支持许多平台。