Search code examples
sql-servertransactionsddlsql-view

Creating Multiple Views in one SQL file


I am trying to create an Install Script for installing Multiple Views at one time. I have tried several suggestions found through out the net with no success. The script will install 6 views and an index.

USE [DB_NAme]
GO
SET XACT_ABORT ON
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

at top of script

Things I have tried:

BEGIN TRANSACTION
  CREATE VIEW [schema].[View_Name]
COMMIT TRANSACTION

error as 'CREATE VIEW' must be the first statement in a query batch.

BEGIN TRANSACTION
    BEGIN TRY
      CREATE VIEW [schema].[View_Name]
    END TRY
    BEGIN CATCH
      ERR CODE
    END CATCH
COMMIT TRANSACTION

with a few other variations.

Looking for a way to several CREATE views in one .sql file:

checks for and drops/creates indexes checks for and DROPS views creates views.. 7 of them


Solution

  • Just separate the definitions with GO:

    CREATE VIEW view1
        SELECT . . .
    GO
    
    CREATE VIEW view2
        SELECT . . .
    GO
    
    . . .