Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Views that use SELECT * need to be recreated if the underlying table changes

Tags:

sql-server

Is there a way to make views that use SELECT * stay in sync with the underlying table.

What I have discovered is that if changes are made to the underlying table, from which all columns are to be selected, the view needs to be 'recreated'. This can be achieved simly by running an ALTER VIEW statement.

However this can lead to some pretty dangerous situations. If you forgot to recreate the view, it will not be returning the correct data. In fact it can be returning seriously messed up data - with the names of the columns all wrong and out of order.

Nothing will pick up that the view is wrong unless you happened to have it covered by a test, or a data integrity check fails. For example, Red Gate SQL Compare doesn't pick up the fact that the view needs to be recreated.

To replicate the problem, try these statements:

CREATE TABLE Foobar (Bar varchar(20))

CREATE VIEW v_Foobar AS SELECT * FROM Foobar

INSERT INTO Foobar (Bar) VALUES ('Hi there')

SELECT * FROM v_Foobar

ALTER TABLE Foobar
ADD Baz varchar(20)

SELECT * FROM v_Foobar

DROP VIEW v_Foobar
DROP TABLE Foobar

I am tempted to stop using SELECT * in views, which will be a PITA. Is there a setting somewhere perhaps that could fix this behaviour?

like image 579
cbp Avatar asked Feb 28 '23 03:02

cbp


1 Answers

You should stop using SELECT *. It can always lead to some "pretty dangerous" situations.

However, as an alternative, you can make your views schema bound. That way you won't be able to change the underlying table without re-creating the view.

like image 75
Robin Day Avatar answered Mar 02 '23 05:03

Robin Day