|
Check If A Login Exists In SQL Server 2008
If you are creating a SQL Server login using a script then it is advisable to check if the login you are creating already exists. If you do not do this then SQL Server will throw an error. For example if I execute this statement when a login with name test_user already exists, I will get the following error.
CREATE LOGIN test_user WITH PASSWORD = 'Password123'
Msg 15025, Level 16, State 1, Line 1 The server principal 'test_user' already exists.
To avoid this a check can be used before creating the login. One way to do this is to write a statement like this.
IF NOT EXISTS(SELECT name FROM master.dbo.syslogins WHERE name = 'test_user') BEGIN CREATE LOGIN test_user WITH PASSWORD = 'Password123' END
The above statement will check for the login and it will only create it if the login does not already exist. This works but it is not the best way to do it in SQL Server 2008. The problem is that we are querying master.dbo.syslogins which is available only for backward compatibility and as per Microsoft it will be removed in future versions. So the best way to do a check before creating a login is to use sys.sql_logins or sys.server_principals system view. Our statement can be re-written in following two ways.
IF NOT EXISTS(SELECT name FROM sys.server_principals WHERE name = 'test_user') BEGIN CREATE LOGIN test_user WITH PASSWORD = 'Password123' END
OR
IF NOT EXISTS(SELECT name FROM sys.sql_logins WHERE name = 'test_user') BEGIN CREATE LOGIN test_user WITH PASSWORD = 'Password123' END
This approach will ensure that your script will work in future versions of SQL Server when Microsoft decides to remove master.dbo.syslogins.
Leave a Reply
Get Updates By Email
Popular Post
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Free Icons And Images With Visual Studio 2008
- Windows 7 Control Panel In Classic Mode
- Dynamic Sort With LINQ
- Use SqlConnection With LINQ To SQL
- StyleCop Tutorial
- Write To Vista Event Log Using C#
- More Details Emerge On Microsoft Master Certification
Tag Cloud
Code Snippets
- Get Current Windows User In C#
- Get Width And Height Of Image In C#
- Get Windows Registry Size With WMI And C#
- Reverse Array Elements Using C#
- Convert Hexadecimal To Number In C#
- Get Free Disk Space Using T-SQL
- SQL Server 2008 – Get All Indexes In A Database
- Get Name Of Current Executing Assembly In C#
- Get CD Or DVD Drive Information Using WMI And C#
- Get Last Row From Table Using LINQ To SQL

