views:

48

answers:

1

I am working on a script, that needs to be run in many different SQL servers. Some of them, shared the same structure, in other words, they are identical, but the filegroups and the DB names are different. This is because is one per client.

Anyway, I would like when running a script, If I chose the wrong DB, it should not be executed. I am trying to mantain a clean DB. here is my example, which only works for dropping a view if exists, but does not work for creating a new one. I also wonder how it would be for creating a stored procedure.

IF EXISTS (SELECT * 
             FROM dbo.sysobjects 
            WHERE id = object_id(N'[dbo].[ContentModDate]') 
              AND OBJECTPROPERTY(id, N'IsView') = 1)
     AND CHARINDEX('Content', DB_NAME()) > 0

DROP VIEW [dbo].[ContentModDate]

GO

  IF (CHARINDEX('Content', DB_NAME()) > 0)
  BEGIN
    CREATE VIEW [dbo].[Rx_ContentModDate] AS  
     SELECT 'Table1' AS TableName, MAX(ModDate) AS ModDate
       FROM Tabl1 WHERE ModDate IS NOT NULL
     UNION 
     SELECT 'Table2', MAX(ModDate) AS ModDate 
       FROM Table2 WHERE ModDate IS NOT NULL
  END
END
GO
+3  A: 

Exactly the same for a stored proc.

I'd also do this too because the code above won't work. CREATE xxxx must usually first in the batch. And your code will also find databases called "ContentFoo"

IF OBJECT_ID('dbo.myView') IS NOT NULL AND DB_NAME() = 'Content'
    DROP VIEW [dbo].[ContentModDate]
GO
IF DB_NAME() = 'Content'
EXEC ('
CREATE VIEW [dbo].[Rx_ContentModDate] AS  
 SELECT ''Table1'' AS TableName, MAX(ModDate) AS ModDate
 FROM Table1 WHERE ModDate IS NOT NULL
UNION 
 SELECT ''Table2'', MAX(ModDate) AS ModDate 
 FROM Table2 WHERE ModDate IS NOT NULL
')

Note: is the view name meant to be different?

gbn
Thanks a lot for the answer. It did work. The view name meant to be the same, I just had a typo in there. I like running scripts that are intended for a given kind of DB. It is because I have more than 50 servers that I need to maintain and I hate by mistake run a SP or function that it was not meant to be run.Thx Again.
Randall Salas