Monday, February 19, 2024

SQL Server View with Check Option

When a view is created then we can add WITH CHECK OPTION after the WHERE condition in SELECT query. If the condition fails then we cannot add row into the view. Look at the following example in this regard.

CREATE TABLE Employees
(
	Id int ,
	first_name varchar(10),
	last_name varchar(10),
	salary int
) 
GO

Create a view based on Employees table.

CREATE VIEW MyVwEmployees
AS SELECT Id, first_name, last_name, salary
FROM Employees
WHERE salary < 50000

Now insert a row into the view.

INSERT INTO MyVwEmployees VALUES(1, 'Akash','Verma',60000)

The row is inserted into table but view will not display the row. 

Now alter the view definition as given below.

ALTER VIEW MyVwEmployees
AS SELECT Id, first_name, last_name, salary
FROM Employees
WHERE salary < 50000
WITH CHECK OPTION

Insert a row as given below.

INSERT INTO MyVwEmployees VALUES(2, 'Rina','Gupta',60000)

The row will not be inserted and following error will be.

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.

No comments:

Post a Comment

Hot Topics