quarta-feira, 30 de março de 2016

Create Procedure inside IF - SQL SERVER

I'm guessing everyone came around a similar problem at one point: you need to create a proc but only if a certain table/object exists or doesnt exists).

Althought I Love T-SQL, one limitation to it is that, CREATE PROCEDURE must be the fisrt statement in your batch. You could add a GO to solve it, but there goes your IF...

But you can "jerry rig" this with dynamic SQL, like this:


IF EXISTS(SELECT * 
          FROM   sys.objects 
          WHERE  NAME = N'YourTable' 
                 AND type = 'U') 
  BEGIN 
      EXEC('create proc YourProc as begin print ''teste'' end;') 
  END 



Cheers!

Check out my new book about R Language http://www.amazon.com/dp/B00SX6WA06

Nenhum comentário:

Postar um comentário

Leave your comment here!