Question : Use of If then statement while creatin a sql view

I want to create an sql command that checks an if condition. If is true it executes an alter view command else it execute a create view. Then, after the IF condition it grants a user group to the view.
But I get an error on END command
 Any help? Is it possible to execute a command ot of the IF condition?
See code attached.
Thanks for support, Gianni.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
-- Check If view all_part exist
IF EXISTS (SELECT * FROM DBO.SYSOBJECTS where name = 'eq_status_pms_MPP')
-- Alter it if, it exist already
    ALTER VIEW "AFM"."eq_status_pms_MPP"
    AS
    select ........
ELSE
-- Create it if, it not exist already
    CREATE VIEW "AFM"."eq_status_pms_MPP"
    AS
    select ......
ENDIF
-- Grant view to AFM_Users group
GRANT ALL ON AFM.eq_status_pms_MPP TO A_USERS
Open in New Window Select All

Answer : Use of If then statement while creatin a sql view

You cannot use the IF..ELSE statements like that with DDL.. DDL statements have to be issued in separate batches - separated by the GO keyword..

Try -
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
SET QUOTED_IDENTIFIER ON
-- Check If view all_part exist
IF EXISTS (SELECT * FROM DBO.SYSOBJECTS where name = 'eq_status_pms_MPP' AND Type = 'V')
	DROP VIEW eq_status_pms_MPP
GO
 
-- Create it if, it not exist already
CREATE VIEW "AFM"."eq_status_pms_MPP"
    AS
    SELECT ......
GO
 
-- Grant view to AFM_Users group
GRANT ALL ON AFM.eq_status_pms_MPP TO A_USERS
GO
Open in New Window Select All
Random Solutions  
 
programming4us programming4us