Can an SQL constraint be used to prevent a particular value being changed when a condition holds?

后端 未结 3 1654
礼貌的吻别
礼貌的吻别 2021-01-05 08:12

I know that SQL constraints can force data to meet validity criteria. However, what about criteria such as \"Student\'s grade can only be updated when the \'finalised\' flag

3条回答
  •  一向
    一向 (楼主)
    2021-01-05 08:57

    Short answer: No, SQL constraints cannot in themselves prevent a change to column Grade when Finalized is 'true' (but allow a change otherwise).

    There are several kinds of SQL constraints: CHECK, DEFAULT, NOT NULL, UNIQUE, Primary Key, and Foreign Key.

    Each of these can limit or affect the values of columns, either singly or in combination, but cannot prevent an UPDATE to values that are allowed. In particular none of these constraints can prevent an UPDATE to Grade and/or Finalized based on the previous values of Grade and Finalized.

    An UPDATE trigger can do this: compare the new and old values of Grade, and if these differ and Finalized = 'true', rollback the UPDATE with an explanatory error message.

    However the application can and should enforce such a "business rule" more gracefully. The rule itself could use a bit of clarification about when the Finalized value can be changed. E.g., is it allowed to change Grade and set Finalized = 'false' at the same time? The trigger logic can handle such details, and it would be reasonable to install that as a failsafe, while making the rules explicit somewhere in the application (frontend/middleware/backend) as well.

提交回复
热议问题