I want to write a stored procedure that checks the environment a database resides in (Based on the name) and creates the appropriate user and role for our application.
This would allow us to automate setting up permissions if we move a database between environments (Currently due to the limitations of Windows Azure SQL Database we have to manually run a script which is not ideal and prone to human error).
So the syntax we are using is:
DECLARE @UserToAdd VARCHAR(50) = (
SELECT CASE
WHEN @Environment = 'Development' THEN 'DevelopmentApplicationUser'
WHEN @Environment = 'Test' THEN 'TestingApplicationUser'
ELSE ''
END
)
IF (@UserToAdd != '')
BEGIN
EXEC ('CREATE USER [' + @UserToAdd + '] FOR LOGIN [' + @UserToAdd + '];')
EXEC ('EXEC sp_addrolemember N''WebUser'', N''' + @UserToAdd + ''';')
END
This works correctly on our development server (SQL Server 2008 R2) but in Windows Azure SQL Database we get the below error:
The CREATE USER statement must be the only statement in the batch
Now the MSDN documentation does state:
If the CREATE USER statement is the only statement in a SQL batch, Windows Azure SQL Database supports the FOR | FROM LOGIN clause. If the CREATE USER statement is not the only statement in a SQL batch or is executed in dynamic SQL, the FOR | FROM LOGIN clause is not supported.
However this means that we cannot automate our permissions whatsoever.
Has anyone got around this issue and been able to produce dynamic sql that creates a user? Alternatively is there a way around this in a stored procedure?
ALTER USER. You can runCREATE USER [x] WITHOUT LOGINhoweverALTER USERwill not let you rebind it to a login