Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server Alembic MSSQL唯一约束允许空值 要解决的问题_Sql Server_Python 3.x_Sqlalchemy_Alembic - Fatal编程技术网

Sql server Alembic MSSQL唯一约束允许空值 要解决的问题

Sql server Alembic MSSQL唯一约束允许空值 要解决的问题,sql-server,python-3.x,sqlalchemy,alembic,Sql Server,Python 3.x,Sqlalchemy,Alembic,使用MSSQL,我希望有一个列是唯一的,并接受空值 问题 将两行数据添加到允许使用唯一约束的空值的列中,如下面的实现中所示,会出现以下错误: Violation of UNIQUE KEY constraint 'UQ_...'. Cannot insert duplicate key in object 'TABLE'. The duplicate key value is (<NULL>). (2627) (SQLExecDirectW)" 在唯一字段中允许空值的解

使用MSSQL,我希望有一个列是唯一的,并接受空值

问题
  • 将两行数据添加到允许使用唯一约束的空值的列中,如下面的实现中所示,会出现以下错误:

    Violation of UNIQUE KEY constraint 'UQ_...'. Cannot insert duplicate key in 
    object 'TABLE'. The duplicate key value is (<NULL>). (2627) (SQLExecDirectW)"
    

    在唯一字段中允许空值的解决方案是:

  • 定义列时不要创建唯一约束
  • op.add\u列(
    'TABLE',sa.Column('reference',sa.Integer(),nullable=True),#无唯一性=True
    )
    
  • 手动创建一个
  • op.create\u索引(
    “uq_reference_allow_nulls”,table_name='table',columns='reference'],
    mssql_其中=sa.text('reference NOT NULL'),unique=True,
    )
    
  • 降级时删除索引
  • op.drop\u index('uq\u reference\u allow\u nulls',table\u name='table')
    
    这也解决了表上随机唯一约束的问题,因为
    unique
    参数被删除。alembic修订版总体上如下所示:

    来自alembic导入操作
    将sqlalchemy作为sa导入
    #...
    def升级():
    op.add_列(
    'TABLE',sa.Column('reference',sa.Integer(),nullable=True),#此处不包含unique
    )
    创建索引(
    “uq_reference_allow_nulls”,table_name='table',columns='reference'],
    mssql_其中=sa.text('reference NOT NULL'),unique=True,
    )
    def降级():
    op.drop\u index('uq\u引用\u允许为空,table\u name='table'))
    op.drop_列('表格','参考')
    
    下面的答案不是这样吗?它在
    升级中
    功能不用担心。我的回答不够清楚:)。我只是扩大了答案。希望这能让事情更清楚一点