SQL条件唯一约束与同一表中的Where子句

时间:2014-01-31 17:28:13

标签: sql sql-server sql-server-2008-r2 conditional unique-constraint

我有一个表格,我希望确保五个列的组合在该表中保持唯一。例如:

ALTER TABLE [dbo].[MyTable] 
    ADD CONSTRAINT [UQ__MyTable.MFG.Model.Class.Depiction.Iteration] 
        UNIQUE NONCLUSTERED 
        (
         [ManufacturerID] ASC,
         [Model] ASC,
         [BlockClassID] ASC,
         [BlockDepictionID] ASC,
         [BlockIterationID] ASC
        )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
            SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, 
            ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) 
    ON [PRIMARY]
GO

我想排除第六个单独列具有特定值的组合。例如,我只想在列[Flag] = 0时强制实施上述约束,并在列[Flag] = 1时排除强制执行。

1 个答案:

答案 0 :(得分:3)

作为解决方法,您可以通过创建唯一的筛选索引在SQL Server 2008及更高版本中获得正确的ANSI行为。

import sys
from PyQt4 import QtGui, QtCore

class Form(QtGui.QWidget):

    def __init__(self, parent):
        super(Form, self).__init__(parent)
        self.lbl = QtGui.QLabel("Test", self)

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(MainWindow, self).__init__()
        self.setGeometry(50, 50, 1600, 900)
        new_window = Form(self)
        self.setCentralWidget(new_window)
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    main_window = MainWindow()
    sys.exit(app.exec_())    

if __name__ == "__main__":
    main()

TechNet article