我想对列强制执行唯一约束,但前提是它不为空。这是 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;
关于python - 使用 SQLAlchemy 和 MS SQL Server 实现 Unique if not Null 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747959/