python - 使用 SQLAlchemy 和 MS SQL Server 实现 Unique if not Null 约束

标签 python sql-server sqlalchemy

我想对列强制执行唯一约束,但前提是它不为空。这是 SQLite 中的默认行为,但在 MS SQL Server 中不是。

在 SQL Server 中完成此操作的方法似乎是使用带有 where 子句的索引,如 this post 中所述。 .我的问题是我如何在 SQLAlchemy 中做到这一点并让它仍然与 SQLite 一起工作。

我想这大概就是我想要的:

class MyClass(Base):
    __tablename__ = 'myclass'
    __table_args__ = (Index('unique_index', <where clause?>, unique=True)
    my_column = Column(Integer) # The column I want unique if not null

哪里<where clause?>是一些将索引放在 my_column 上的表达式它不在哪里 NULL .这似乎可以通过阅读 documentation 来实现。对于索引,但我不知道我需要什么表达式。非常感谢您提供有关此方法或其他方法的帮助。

最佳答案

SQL Server 使用过滤索引的解决方案:

CREATE TABLE tab(col INT);
CREATE UNIQUE INDEX uq_tab_col ON tab(col) WHERE col IS NOT NULL;

INSERT INTO tab(col) VALUES (1),(2),(NULL),(NULL);

-- INSERT INTO tab(col) VALUES (1);
-- Cannot insert duplicate key row in object 'dbo.tab' with unique index 'uq_tab_col'.
-- The duplicate key value is (1).

SELECT * FROM tab;

LiveDemo

关于python - 使用 SQLAlchemy 和 MS SQL Server 实现 Unique if not Null 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747959/

相关文章:

python - 使用python中的套接字编程将视频流从服务器发送到客户端

python - numpy:填充数组的子集

java - 如何使用 hibernate 读取地理值?

sql - 将 float 转换为 varchar 时 0 * - 1 = -0 奇怪的结果

python - sqlalchemy:获取受批量删除影响的行

python - 尝试使用 Twitter API 验证应用程序时出现 403 错误

python - Django:注释多个查询

SQL Server : How to de-duplicate on two columns/conditions?

sqlite - 在事件监听器中创建数据库触发器

python - "where()"在 SQLAlchemy 中如何工作