How to add windows user as a SQL users in windows authentication mode

Shima.Y picture Shima.Y · Jan 11, 2016 · Viewed 12.4k times · Source

I want to add windows user to SQL users pragmatically. my problem is that I want to do this on systems that have SQL installed in mixed mode but I don't have username and password , I just know the instance name and I don't know how can I execute my script of adding windows user to SQL users in this situation.

I know the script is :

use master
GO

create login [<YourDomain>\User1] from windows;
GO

my connection string is :

ServerConnection myServerConnection = new ServerConnection(myinstancename);
Server myServer = new Server(myServerConnection);

SqlConnection scSqlConnction = new SqlConnection(myServerConnection.ConnectionString);

but when I create a server connection with my instance name, and want to execute script with related connection string I get the error of

login failed for user (windows user)

Answer

Ahmed Galal picture Ahmed Galal · Jan 11, 2016

You Can try this code Must be have UserName in your windows

Windows Login :

CREATE LOGIN [YourDomain\UserName] FROM WINDOWS WITH DEFAULT_DATABASE= master
GO
ALTER SERVER ROLE [sysadmin] 
ADD MEMBER [YourDomain\UserName]
GO

SQL Login

CREATE LOGIN UserName 
    WITH PASSWORD = N'Password' 
    MUST_CHANGE,
    CHECK_POLICY = ON;
GO