Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL view with "with check option"

Tags:

sql

sql-server

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.

like image 839
pete Avatar asked Jan 29 '17 16:01

pete


People also ask

How do I add a check option to view?

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.

What is with check option in Oracle view?

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.

What is the result of the with check option in a view that has a WHERE clause in its select statement?

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.

What happens when the with check option is not specified in the CREATE VIEW 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.


1 Answers

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'

like image 133
igelr Avatar answered Oct 03 '22 02:10

igelr