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?
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).
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.
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.
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
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
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