[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

SQL Query syntax : IF NOT EXISTS?

Posted on 2009-05-13
6
Medium Priority
?
1,929 Views
Last Modified: 2012-05-06
First I creat a Login to SQL Server using

CREATE LOGIN NT AUTHORITY\NETWORK SERVICE FROM WINDOWS WITH DEFAULT_DATABASE="MyDB";

Here, NT AUTHORITY\NETWORK SERVICE is the name of the Login I created and MyDB is the DataBase I associate it with.

After creating it I need to change some settings of the created login. Following is the manual procedure I usually do.

1. Open SQL Server Management Studio
2. In the "Object Explorer", expand "Security" -> "Logins"
3. Right Click the newly created login "NT AUTHORITY\NETWORK SERVICE" -> Select "Properties"
4. In the "Select a page" section select "User Mapping"
5. In the right hand side, there is a section called "Users mapped to this login". There, under the "Map" section check the CheckBox relavent to MyDB, then under "Default Schema" click the button that appears.
6. In the appearing "Select Schema" windown, click "Browse", select MyDB from the new window that opens and click OK. Then press OK in the "Select Schema" window and return to the previous window. (Bear in mind that at the time of the creation of MyDB, I also create Schemas, so that I am able to select that from "Select Schema" window. In your PC, you may not be able to do so if you don't create a schema when you create a DB.)
7. There, in the part at the bottom which says "Database role membership for : MyDB", check "db_owner". ("public" is already checked, so leave it as it is)
8. Then click OK in the Login Properties and apply the above settings.

I need this process to be done using SQL Queries, so following is the query I use.

But not just that, I also want to check if the login and the users exist before they are created.

I manged to check for the login using the following:


IF EXISTS (select loginname from master.dbo.syslogins where name = N'NT AUTHORITY\NETWORK SERVICE' and dbname = 'MyDB')

That worked fine, but I don't know how I should look for the users if they exist or not.
Any ideas?
Help with code segments will be greatly appreciated.
USE [MyDB]
GO
ALTER LOGIN [MyLogin] WITH DEFAULT_DATABASE=[MyDB]
GO
USE [MyDB]
GO
CREATE USER [MyLogin] FOR LOGIN [MyLogin]
GO
USE [MyDB]
GO
ALTER USER [MyLogin] WITH DEFAULT_SCHEMA=[mySchema]
GO
USE [MyDB]
GO
EXEC sp_addrolemember N'db_owner', N'MyLogin'
GO

Open in new window

0
Comment
Question by:sachintha81
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 31

Expert Comment

by:RiteshShah
ID: 24372076
you can check whether user exist or not from following query

user DataBaseName
SELECT name FROM sysusers
0
 
LVL 31

Expert Comment

by:RiteshShah
ID: 24372083


Declare @userName varchar(50)
set @UserName='Ritesh123'


if exists(SELECT name FROM sysusers where name=@Username)
print 'exists'
else
print 'not exists'

0
 
LVL 1

Expert Comment

by:Kerjemanov
ID: 24372351
if exists(select * from sys.syslogins WHERE name = 'sa') ...
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 31

Accepted Solution

by:
RiteshShah earned 200 total points
ID: 24372370
kerjemanov,

you gave the right solution but for checking login not use. I gave reference of SysUsers after reading

" but I don't know how I should look for the users if they exist or not" from Author's post.

if author wants to check for users than he should go for

Declare @userName varchar(50)
set @UserName='Ritesh123'


if exists(SELECT name FROM sysusers where name=@Username)
print 'exists'
else
print 'not exists'


and if he wants to check for logins than he should go for


Declare @LoginName varchar(50)
set @LoginName='Ritesh123'


if exists(SELECT name FROM sys.syslogins where name=@Username)
print 'exists'
else
print 'not exists'

0
 
LVL 1

Expert Comment

by:Kerjemanov
ID: 24372971
Author talked about logins, so I thought may be he just got confused login with user
0
 
LVL 3

Author Comment

by:sachintha81
ID: 24380943
Actually I wanted to check for both logins and users, but had already figured out a way to check for logins as I've shown in my first post. Though it is a bit different from what Ritesh has shown.

Anyway, thank you for clearing both of them out. Excellent answer!
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question