I want to create a number of database users on two sql server instances. To be able to easily copy databases from one instance to another, I want the SIDs to be consistent.
My idea was to use predictable SIDs, to minimize maintenance pain. I a dreaming about something like this:
CREATE LOGIN newuser1 WITH PASSWORD = '...', SID = CAST('newuser1' AS BINARY(16))
-- or alternatively:
CREATE LOGIN newuser1 WITH PASSWORD = '...', SID = HASHBYTES('newuser1')
Calculating values for the SID, however, seems not to be supported by the CREATE LOGIN command:
Meldung 102, Ebene 15, Status 1, Zeile 1
Falsche Syntax in der Nähe von "SID". -- Wrong syntax near "SID"
How can I use a calculated value for SID?
This can be accomplished by assembling the sql statement in a variable and the executing it with sp_executesql:
DECLARE @SQL nvarchar(4000)
SET @SQL = 'CREATE LOGIN newuser1 WITH PASSWORD = ''...'', SID = 0x'+CONVERT(VARCHAR(1000), CAST('newuser1' AS binary(16)), 2)
PRINT @SQL
EXEC sp_executesql @SQL
Alternatively, if you want to reuse this approach, you can use create a stored procedure:
CREATE PROCEDURE create_user_with_predictable_sid
@UserName varchar(256),
@Password varchar(256)
AS
DECLARE @SQL nvarchar(4000) = 'CREATE LOGIN '+@UserName+' WITH PASSWORD = '''+@Password+''', SID = 0x'+CONVERT(VARCHAR(1000), CAST(@UserName AS binary(16)), 2)
PRINT @SQL
EXEC sp_executesql @SQL
GO
GO
create_user_with_predictable_sid 'newuser1', '...'
GO
DROP PROCEDURE create_user_with_predictable_sid
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With