Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating readonly views in Sql Server

According to MSDN, views composed of simple selects automatically allow you to use insert/update/delete statements on the table. Is there a way to prevent this - to tell Sql Server that the view is readonly, and you can't use it to modify the table?

like image 910
Idan Arye Avatar asked Oct 18 '11 10:10

Idan Arye


People also ask

How do I create a readonly view?

A view is read-only if it is not deletable, updatable, or insertable. A view can be read-only if it is a view that does not comply with at least one of the rules for deletable views. The READONLY column in the SYSCAT. VIEWS catalog view indicates a view is read-only (R).

Can you create views with read only access?

The creator of the view must have the following privileges: To create a read-only view, the creator needs SELECT privileges for any underlying tables. To create an update-able view, the creator needs ALL privileges to the underlying tables.

Which clause will create read only views?

Read-Only Views A view will be read-only if its SELECT statement has any of the following characteristics: Specifies a row quantifier other than ALL (i.e., DISTINCT, FIRST, SKIP) Contains fields defined by subqueries or other expressions. Contains fields defined by aggregating functions and/or a GROUP BY clause.


2 Answers

The best way would be to remove UPDATE/DELETE/INSERT permissions on the View.

Apart from that you could create an INSTEAD OF trigger on the view that simply does nothing to have the updates silently fail or there are quite a few constructs that make views non updatable. So you can pick one that doesn't change semantics or efficiency and then violate it.

Edit: The below seems to fit the bill.

CREATE VIEW Bar
AS
SELECT TOP 100 PERCENT x
FROM foo
WITH CHECK OPTION
like image 119
Martin Smith Avatar answered Oct 05 '22 11:10

Martin Smith


You could specify an UNION operator in order to make SQL Server fail during the INSERT/UPDATE/DELETE operation, like this:

create view SampleView
as
  select ID, value from table
  union all
  select 0, '0' where 1=0

The last query doesn't return any rows at all, but must have the same amount of fields with the same data types as the first query, in order to use the UNION safely. See this link for more info: Different ways to make a table read only in a SQL Server database

like image 30
Guillermo Gutiérrez Avatar answered Oct 05 '22 11:10

Guillermo Gutiérrez