开发者

Create view or SP, only if the DB contains a pattern

I am working on a script, that needs to be run in many different SQL servers. Some of them, shared the same structure, in othe开发者_StackOverflow中文版r 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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜