Avatar of LuckyLucks
LuckyLucks asked on

MS SQL server 2012 query

Hi:

 I am looking to drop and recreate a view, if its exists, and Grant a role to it. I have the skeleton below that doesn't work, could you advise me of the correction?

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

DROP VIEW  [dbo].[myView];

CREATE VIEW [dbo].[myView]
AS
SELECT
   COl1,
   COl2
  FROM Table T
GO

GRANT ROLE myROLE to  [dbo].[myView]
Microsoft SQL ServerSQL

Avatar of undefined
Last Comment
Chris Luttrell

8/22/2022 - Mon
SOLUTION
Jim Horn

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
LuckyLucks

So, it becomes?

IF EXISTS (SELECT name FROM sys.views WHERE name='myView')
   DROP VIEW  [dbo].[myView]
GO

CREATE VIEW [dbo].[myView]
AS
blah

GO
Jim Horn

Correct.  That way it drops only if it already exists, potentially avoiding a 'you tried to drop a view that does not exist' error.
ASKER CERTIFIED SOLUTION
Chris Luttrell

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes