如何在触发器中更改运行时数据库名称

时间:2014-07-08 09:20:33

标签: mysql sql-server-2008 sql-server-2005

USE [AlphaGlobal]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[TrInsertLocalUser]
   ON  [dbo].[Users]
   AFTER  INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
  insert into AlphaLocal12.dbo.Users (PkUserId,Name,Address)
                                     values(
                                       (Select inserted.PkUserId from inserted),
                                       (Select inserted.Name from inserted),
                                       (Select inserted.Address from inserted),
                                       (Select inserted.ZIPCode from inserted)
                                     )

END

听到我想更改运行时插入查询数据库名称,如(AlphaLocal13AlphaLocal14)。

那么如何更改数据库名称?

1 个答案:

答案 0 :(得分:0)

这是一个可能的方法:

USE [AlphaGlobal]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[TrInsertLocalUser]
   ON  [dbo].[Users]
   AFTER  INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
  DECLARE @YourDBNAME varchar(30)
  SET @YourDBNAME = 'MYDBNAME'
  SET @sqlCommand = 'insert into '+ @YourDBNAME+ '.dbo.Users (PkUserId,Name,Address)
                                       values(
                                         (Select inserted.PkUserId from inserted),
                                         (Select inserted.Name from inserted),
                                         (Select inserted.Address from inserted),
                                         (Select inserted.ZIPCode from inserted))';
  EXEC (@sqlCommand)
END

@yourDBNAME应该在您的程序中相应更改。