【问题标题】:Error when changing PrimaryKey (constraint) in table更改表中的 PrimaryKey(约束)时出错
【发布时间】:2016-11-14 13:39:01
【问题描述】:

更改表中的 PrimaryKey 时出现问题。

错误:“无法在可为空的列上创建 IDENTITY 属性。”

详情

  • “update”是类的可枚举,派生自DataSourceObject和IClonable
  • “table”是从DataSourceObject派生的类

代码

foreach (var u in update)
{
   myList.Add(string.Format("alter table [{0}] alter column {1} {2} {3};", table.Name, u.Name, (u.IsPrimary || u.IsAutoIncrement) ? "not null" : "null"));
}

我也尝试过像这样删除所有 PrimaryKey:

foreach (var u in update.Where(x => x.IsPrimary))
{    
   myList.Add(string.Format("alter table [{0}] drop constraint {1}", table.Name, u.Name));
}

但它说我试图设置为 PrimaryKey 的当前项目不是约束。

我还提到,如果我以这种方式更改 if 语句(反之亦然):

(u.IsPrimary || u.IsAutoIncrement) ? "null" : "not null";

当我尝试改回主键时,它可以工作。我的意思是,如果我先更改主键,那么就会出现异常,然后我更改 if 语句,然后更改 PrimaryKey 就可以了。

更新:现在我肯定知道我必须找到一个我想要删除的约束名称,在我的情况下,它将是默认的 - ID(可以使用 sys 模式完成,但是我不知道怎么用),那我就得丢掉它,毕竟我要生成一个新名字的新约束。

【问题讨论】:

    标签: c# sql linq tsql ado.net


    【解决方案1】:

    结果查询:

    declare @CONSTRAINTNAME varchar(128);
    declare @script nvarchar(max);
    
    select top 1 @CONSTRAINTNAME = t1.CONSTRAINT_NAME
    from INFORMATION_SCHEMA.TABLE_CONSTRAINTS t1
    where CONSTRAINT_TYPE = 'PRIMARY KEY' and upper(t1.TABLE_NAME) = @tableName;
    
    set @script = N'alter table [' + @tableName + N'] drop constraint [' + @CONSTRAINTNAME + N']';
    exec sp_executesql @script
    
    set @script = N'alter table [' + @tableName + N'] add constraint [' + @tableName + '_' + @columnName + N'] primary key (['+ @columnName +'])';
    exec sp_executesql @script
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 2023-03-04
      • 2016-06-11
      相关资源
      最近更新 更多