Question

I have a table of system users each of whom need a database user of their own that the system uses to access the DB(Not my idea..). The system has it's own login. This is creating a problem with the SQL AlwaysOn distributed server setup we're testing because users won't sync between databases. So although the system creates the database users, they won't propogate to the secondary node and when a fallover happens these users can't log in.

So that's my justification for wanting to write a script that creates a DB user from a table in the DB. So, why doesn't the following work and how could I make it work?

DECLARE @foo VARCHAR(250)
SET @foo = (SELECT USER_NAME FROM USER_TABLE WHERE USER_ID = 1337)    
CREATE USER @foo

Currently I get incorrect syntax near '@foo'

Was it helpful?

Solution

DECLARE @foo VARCHAR(250), @execString NVARCHAR(MAX)
SET @foo = (SELECT USER_NAME FROM USER_TABLE WHERE USER_ID = 1337)    

SET @execString = 'CREATE USER ' + @foo
EXECUTE sp_executesql @execString
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top