17

How can I create a SQL user in a SQL Server Express database that I added to my project?

I need to create a user to use in a connection string that doesn't use Integrated Security.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
John Egbert
  • 5,496
  • 8
  • 32
  • 44

2 Answers2

35

You would need to create a SQL Authenticated login first with CREATE LOGIN then add a user associated with that login to your database by using CREATE USER.

USE [master]
GO
CREATE LOGIN [JohnEgbert] WITH PASSWORD=N'YourPassword', 
                 DEFAULT_DATABASE=[YourDB], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
USE [YourDB]
GO
CREATE USER [JohnEgbert] FOR LOGIN [JohnEgbert] WITH DEFAULT_SCHEMA=[dbo]
GO
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
15

If you create a SQL login and a SQL user without errors, but then get an error when trying to connect, you may have the SQL Authentication mode disabled. To check, run:

SELECT SERVERPROPERTY('IsIntegratedSecurityOnly')

If this returns 1, then SQL Authentication (mixed mode) is disabled. You can change this setting using SSMS, regedit, or T-SQL:

EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2

Then restart the SQL Server service, and create a login and a user, here with full permissions:

CREATE LOGIN myusername WITH PASSWORD=N'mypassword', 
                 DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF

EXEC sp_addsrvrolemember 'myusername', 'sysadmin'
CREATE USER myusername FOR LOGIN myusername WITH DEFAULT_SCHEMA=[dbo]
Tom Andraszek
  • 1,793
  • 1
  • 23
  • 30
  • 5
    Note I had the same issue that you mention here, but solved it right clicking on my DB serve '(local)\sqlexpress'-->Properties->Security. There is a radio button for Server Authentication with two options: 1) Windows Authentication Mode 2) SQL Server and Windows Authentication Mode. My initial setting was 'Windows Authentication Mode' and I changed to #2 (both). After that I as able to log in with Sql Server Authentication. – seeking27 Dec 13 '16 at 19:30
  • Extremely helpful advice from both of you - thank you :) – beginAgain Feb 07 '19 at 17:48
  • That was it. Mixed mode wasn't turned on. – Thomas Eyde Oct 15 '19 at 09:50