Create OR Replace View in SQL Server

Hi, I have the following view in MS SQL Server which is perfect.

Problem: I run a script to create or alter tables. Similarly I need to check if the view by view name exists, if yes, drop and recreate. How can I do this

CREATE VIEW VCURRENTDATE AS
SELECT RIGHT('0' + CAST(DATEPART(D, GETDATE()) AS NVARCHAR(2)), 2)
+ '/' + RIGHT('0' + CAST(DATEPART(M, GETDATE()) AS NVARCHAR(2)), 2)
+ '/' + CAST(YEAR(GETDATE()) AS NVARCHAR(4)) + ' ' + RIGHT('0'
+ LTRIM(STUFF(RIGHT(CONVERT(CHAR(26), CURRENT_TIMESTAMP, 109), 14),9, 4, ' ')),11)
AS CURRENTDATETIME
GRChandrashekarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
IF EXISTS (SELECT * FROM sys.views WHERE name = 'YourView')
   DROP VIEW YourView
GO

CREATE VIEW YourView (blah blah blah..

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chris MConsulting - Technology ServicesCommented:
For tables use this kinda query:

if exists (select * from sysobjects where name='my_table' and xtype='U')
       drop table [my_table];
go

create table [my_table] ( ..... etc )
go

Open in new window


For views use this:

if exists (select * from sysobjects where name='my_view' and xtype='V')
       drop view [my_view];
go

create view [my_view] as  ..... etc 
go

Open in new window

0
Chris MConsulting - Technology ServicesCommented:
To change an existing view, you can also use "ALTER VIEW [my_view] as ....."
0
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Thanks for the grade.  Good luck with your project.  -Jim
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.