我在SSMS(2014)中生成了一些创建脚本,作为脚本的一部分,创建了几个帐户。我们将根据数据库是否部署用于测试,预生产或生产来使用不同的帐户。
我想让安装程序更容易更改帐户,所以我认为如果我可以存储登录并在脚本的最顶部声明这将是一个好主意,但是我不知道如何要解决这个问题。
目前我有:
CREATE USER [RAMBOLL\SVC_D-StructureDB] FOR LOGIN [somedomain\someaccount] WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE [db_datareader] ADD MEMBER [somedomain\someaccount]
GO
ALTER ROLE [db_datawriter] ADD MEMBER [somedomain\someaccount]
GO
如何声明“somedomain \ someaccount”然后在上面的SQL代码中引用它?我试过但SQL不喜欢它。
DECLARE @SomeAccount VARCHAR(255)
SET @SomeAccount = "[somedomain\someaccount]"
CREATE USER @SomeAccount FOR LOGIN @SomeAccount WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE [db_datareader] ADD MEMBER @SomeAccount
GO
ALTER ROLE [db_datawriter] ADD MEMBER @SomeAccount
GO
这些遗留的和将要删除的存储过程允许参数化
但是,如果只有几个选项,我会考虑IF声明。然后动态SQL,如果你需要更多的灵活性
DECLARE @env VARCHAR(10)
SET @env = 'test'
IF @env = 'test'
BEGIN
CREATE USER [somedomain\someaccount] FOR LOGIN [somedomain\someaccount] WITH DEFAULT_SCHEMA=[dbo]
ALTER ROLE [db_datareader] ADD MEMBER [somedomain\someaccount]
ALTER ROLE [db_datawriter] ADD MEMBER [somedomain\someaccount]
END
ELSE IF @env = 'live'
BEGIN
CREATE USER [somedomain\liveaccount] FOR LOGIN [somedomain\liveaccount]WITH DEFAULT_SCHEMA=[dbo]
ALTER ROLE [db_datareader] ADD MEMBER [somedomain\liveaccount]
ALTER ROLE [db_datawriter] ADD MEMBER [somedomain\liveaccount]
END
...