7

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)

8
  • You need to be able to log in to do anything. If you can't log in you're out of luck. Commented Jan 11, 2016 at 8:20
  • would you please help me by code ? creating a server connection with instance name isn't enough? Commented Jan 11, 2016 at 8:23
  • You don't have access to the SQL Server so no amount of code will help - you can't log in. Commented Jan 11, 2016 at 8:23
  • 1. Can you confirm that 'User1' exists in 'YourDomain'? 2. Have you tried to add this User1 via the SQL Server Management Studio? 3. You could add your ConnectionString to the Question, maybe there is something wrong here. Commented Jan 11, 2016 at 8:34
  • yes I can add this user via SQL Server Management Studio when I have Username and password but in many cases I dont have username and password and I want to create a database in windows mode so I need to add windows user to SQL Users Commented Jan 11, 2016 at 8:48

1 Answer 1

14

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.