开发者

Script a user to a specific database?

I am working on my SQL deployment script.

I have a login named "User123", I have added to my current database, but I have a stored procedure that logs information to MyDB, I need User123 permissions at MyDB 开发者_JAVA百科so I created a user at MyDB with permissions, however how do I script this rather than adding the user manually..

I have this so far, but cant seem to figure out how to add it to the other database, "MyDB" can be hard coded as there will only be 1 on each server, however i cant hard code the current database im running script on

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'User123')
BEGIN
   CREATE USER [User123] FOR LOGIN [User123] WITH DEFAULT_SCHEMA=[dbo]
END
GO

This only runs on current database, how do I make it run against other db.

Example..

MyDB
  Security

   User123

DB1

  Security

   User123

i want a script that will add the user to both current database and "MyDB", without having to manually switch databases


What about:

USE MyDB
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'User123')
BEGIN
   CREATE USER [User123] FOR LOGIN [User123] WITH DEFAULT_SCHEMA=[dbo]
END
GO

USE DB1
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'User123')
BEGIN
   CREATE USER [User123] FOR LOGIN [User123] WITH DEFAULT_SCHEMA=[dbo]
END
GO
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜