T-SQL: Schemabinding

A view is simply a virtual table or a stored select statement.

One option with creating views that I recently came across is the SCHEMABINDING option.
Basically, the SCHEMABINDING option “locks” the table design of a view’s underlying table(s) so that they cannot be changed. Without SCHEMABINDING, you could have the following scenario:

CREATE VIEW MyView
AS
SELECT ColumnA
, ColumnB
, ColumnC
FROM MyTable

Suppose you then alter the table MyTable to remove ColumnC. This would break the view MyView because it refers to the now non-existent ColumnC from MyTable.

If, on the other hand, we created MyView in the following way:

CREATE VIEW MyView WITH SCHEMABINDING
AS
SELECT ColumnA
, ColumnB
, ColumnC
FROM MyTable

and attempted to then delete column ColumnC from MyTable, we would get a warning message that this is not possible since the table is bound to view MyView. Note that this warning occurs whether you are removing or adding a column to the underlying table.

If you really did want to make a change to the table, you would first have to alter the view to remove the WITH SCHEMABINDING option, then make the table change.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.