views:

24

answers:

2

I'm trying to figure out the syntax for creating a view (or function) but only if a dependent CLR assembly exits.

I've tried both

IF EXISTS (SELECT name FROM sys.assemblies WHERE name = 'MyCLRAssembly') 
begin
create view dbo.MyView as select GETDATE() as C1
end

and

IF EXISTS (SELECT name FROM sys.assemblies WHERE name = 'MyCLRAssembly') 
create view dbo.MyView as select GETDATE() as C1
go

Neither work. I get

Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'view'.

How can this be done?

A: 

This is strange for me, but what I see in MSDN is "CREATE VIEW must be the first statement in a query batch." So it looks like you cannot create views inside IF statement.

Andrew Bezzub
+1  A: 

Here is workaround

if object_id('MyView','V') is null
    exec ( 'create view dbo.MyView as select GETDATE() as C1' )
Sparky
this language is so broken
Scott Weinstein
Well, that is why there are so many work-arounds...
Sparky
But the work-around is broken. It means I don't get syntax checking/color formatting on my view code at design time.
Scott Weinstein