I am currently reading the documentation from Microsoft about views and I am kind of confused on what I read about the "with check option." There isn't any examples provided in the documentation. Can someone make me a simple example? I understand easier with examples.
CHECK OPTION Forces all data modification statements executed against the view to follow the criteria set within select_statement. When a row is modified through a view, the WITH CHECK OPTION makes sure the data remains visible through the view after the modification is committed.
To ensure the consistency of the view, you use the WITH CHECK OPTION clause when you create or modify the view. The WITH CHECK OPTION is an optional clause of the CREATE VIEW statement. The WITH CHECK OPTION prevents a view from updating or inserting rows that are not visible through it.
The WITH CHECK OPTION clause can be given for an updatable view to prevent inserts to rows for which the WHERE clause in the select_statement is not true.
If this view is used in a SELECT statement, the conditional (WHERE clause) would be invoked and the resulting table would only contain the matching rows of data. In other words, the WITH CHECK OPTION does not affect the result of a SELECT statement.
The update to the mycolumn column is rolled back, because the updated rows fail the mycolumn = 10 qualification specified in the view definition. If the WITH CHECK OPTION is omitted, any row in the view can be updated, even if the update results in a row that is no longer a part of the view.
Let's understand using the following example
CREATE VIEW PortlandAreaAddresses_vw
AS
SELECT AddressID,
AddressLine1,
City,
StateProvinceID,
PostalCode,
ModifiedDate
FROM Person.Address
WHERE PostalCode LIKE ‘970%’
OR PostalCode LIKE ‘971%’
OR PostalCode LIKE ‘972%’
OR PostalCode LIKE ‘986[6-9]%’
WITH CHECK OPTION;
In this case, if you try to insert a record, CHECK OPTION will enforce to to follow the 4 rules specified for PostalCode
WHERE PostalCode LIKE ‘970%’
OR PostalCode LIKE ‘971%’
OR PostalCode LIKE ‘972%’
OR PostalCode LIKE ‘986[6-9]%’
That means you can't insert a PostalCode like '19970'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With