Why should CREATE VIEW be the first expression in a package?

Is there a logical reason why CREATE VIEW should be the first statement in a package? What is the rationale for this design?

+5
source share
1 answer

It is not that it should be the first statement in the package, but rather that it should be the only expression in the package. For the same reason, CREATE PROCEDURE , CREATE FUNCTION , etc. Everyone should be in their own party ... they need to be compiled independently of another code. One reason is to ensure that anything in the package created before the object actually exists when it is created, and anything that refers to the object after that has what it points to. Another way to help prevent this stuff:

 -- some other code here CREATE PROCEDURE dbo.whatever AS -- procedure code here -- some other code here 

We do not want β€œsome other code here” to be included in the definition of a stored procedure. We would also not know what to do about it:

 CREATE PROCEDURE dbo.proc1 AS -- some code here -- a comment here CREATE PROCEDURE dbo.proc2 AS 

Since we can legitimately post comments before CREATE PROCEDURE , how does the analyzer know which object the comment belongs to?

And for nit-picky, the same goes for submissions. (Note that the procedure was used in the example simply because the procedure can contain several statements, and the view cannot, and a procedure with several statements is much more common than a view with several comments.) But we can demonstrate the same type of problem - ask yourself if you will divide the two performances into your own parties, how do you know what kind of comment4 should have?

 -- comment1 CREATE VIEW dbo.view1 AS -- comment2 SELECT -- comment3 * from sys.objects -- comment4 CREATE VIEW dbo.view2 AS -- comment5 SELECT -- comment6 * from sys.objects 

In Management Studio, you work around this by placing GO between object scripts. Note that GO not T-SQL; it is a batch application separator; from other interfaces you will have to transfer your parties separately in other ways.

Again, the answer in the first sentence: a script to create or modify any module in SQL Server - including views, procedures, functions, and triggers - should be the only expression in the package .

+14
source

Source: https://habr.com/ru/post/1499136/


All Articles