I am trying to create a SQL Server login following the creation of a database through script. The login is local to the host PC and this script will be run on multiple hosts.
What I want to do is the following:
USING MyDatabase
CREATE MyUser FOR LOGIN USER <computer name>/MyUser
What I don't know how to do is incorporate the computer name (ex. Location0001) into this statement.
The login does exist on each machine AND is already listed on the SQL Server as it has access to other databases there.
If it's relevant, the script should be able to run on SQL Server 2008.
The login would look like this for each machine:
Location0001\MyUser
Location0002\MyUser
Location0999\MyUser
Any help would be appreciate, thanks.
Edit: My final solution based on the accepted answ开发者_运维百科er is as follows:
DECLARE @cmd VARCHAR(200)
SET @cmd = N'CREATE USER [MyUser] FOR LOGIN [' + HOST_NAME() + '\MyUser]'
EXEC (@cmd)
You can use the @@servername property to get the name of the machine: select @@servername
declare @cmd varchar(200), @username varchar(50)
set @username = 'testuser'
set @cmd = '
USE MyDatabase
CREATE USER MyUser FOR LOGIN '+@@servername+'\'+@username
PRINT @cmd
EXEC (@cmd)
精彩评论