Link to home
Start Free TrialLog in
Avatar of BrianKwan
BrianKwan

asked on

Easy query

Suppose I have a user name called "Tom" and a database called "testDB"
How can I add the user to the database by query?

I have tried "exec sp_adduser Tom, testDB", but it gives me
"[Microsoft][ODBC SQL Server Driver][SQL Server][ The Login already has
an account under a different user name".

why is it?

Brian
ASKER CERTIFIED SOLUTION
Avatar of chigrik
chigrik

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Guy Hengel [angelIII / a3]
If the login TOM has already a user (whatever name) in the given database, you won't be able to add him a second time.
If you can't see the user TOM in the database, this may result from a backup of your database from a different server. you may then use the sp_dropuser command first.
Hope this helps
You have to execute sp_adduser in the target database and supply the username and loginname.

So to go further on chigrik's answer:

use master
go
sp_addlogin 'Tom','password', 'testDB'
go
use testDB
go
sp_adduser 'Tom','Tom'
go

You may be able to skip the addlogin if it already exists...
the use database  is the main issue I guess.