SQL view with "with check option"

Below is an example that shows the CHECK OPTION behavior.

CREATE TABLE dbo.Table1(Col1 int);
CREATE TABLE dbo.Table2(Col2 int);
INSERT INTO dbo.Table1 (Col1) VALUES(1);
INSERT INTO dbo.Table2 (Col2) VALUES(1);
GO

CREATE VIEW dbo.ViewWithCheckOption
AS
SELECT Table1.Col1, Table2.Col2
FROM dbo.Table1
JOIN dbo.Table2 ON Table1.Col1 = Table2.Col2
WITH CHECK OPTION;
GO

CREATE VIEW dbo.ViewWithoutCheckOption
AS
SELECT Table1.Col1, Table2.Col2
FROM dbo.Table1
JOIN dbo.Table2 ON Table1.Col1 = Table2.Col2;
GO

SELECT Col1, Col1 FROM dbo.ViewWithoutCheckOption; --returns 1 row
INSERT INTO dbo.ViewWithoutCheckOption(Col1) VALUES(2); --succeeds
SELECT Col1, Col1 FROM dbo.ViewWithoutCheckOption; --still returns 1 row

SELECT Col1, Col1 FROM dbo.ViewWithCheckOption; --returns 1 row
INSERT INTO dbo.ViewWithCheckOption(Col1) VALUES(2); -- fails with error 

The error returned is:

Msg 550, Level 16, State 1, Line 30 The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did not qualify under the CHECK OPTION constraint.


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'


Doesn't that mean that you can't make such update via the view, that the row(s) would disappear from the view because of whatever where statement you have in the view would not match the row anymore.

View:

create view xxx as select * from table where status = 1

update using the table (ok):

update table set status = 2 where id = 3

update using the view (not ok):

update xxx set status = 2 where id = 3

and if you would do this, it would make the row disappear

Tags:

Sql

Sql Server