Home

Introduction to Databases

 

Introduction to Database Creation

 

Overview

A database is primarily a group of computer files that each has a name and a location. Just as there are different ways to connect to a server, in the same way, there are different ways to create a database.

Introduction to Databases    

To visually create a new database in Microsoft SQL Server Management Studio, in the Object Explorer, you can right-click the Databases node and click New Database... This would open the New Database dialog box.

Practical LearningPractical Learning: Introducing Databases

  1. All Computers: Start the computer and log in using your domain account
  2. Server: Launch Microsoft SQL Server. In the Server Name combo box, make sure the name of the computer is selected. In the Authentication combo box, make sure Windows Authentication is selected. Make sure the account you are using is selected in the User Name combo box. Click Connect
  3. Each Student:
    1. Start Microsoft SQL Server
    2. In the Server Name combo box, select the name of the server or type it
    3. In the Authentication combo box, select SQL Server Authentication
    4. In the User Name combo box, type the name of the domain, followed by \, and followed by the login name you were given
    5. In the Password combo box, type your password
    6. Click Connect

The Name of a Database

Probably the most important requirement of creating a database is to give it a name. Transact-SQL is very flexible when it comes to names. In fact, it is very less restrictive than most other computer languages. Still, there are rules you must follow when naming a database:

  • A name can start with either a letter (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z), a digit (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), an underscore (_) or a non-readable character. Examples are _n, act, %783, Second
  • After the first character (letter, digit, underscore, or symbol), the name can have combinations of underscores, letters, digits, or symbols. Examples are _n24 or act_52_t
  • A name can include spaces. Example are c0untries st@ts, govmnt (records), or gl0b# $urvey||

Because of the flexibility of Transact-SQL, it can be difficult to maintain names in a database. Based on this, there are conventions we will use for our objects. In fact, we will adopt the rules used in C/C++, C#, Pascal, Java, and Visual Basic, etc. In our databases:

  • Unless stated otherwise (we will mention the exceptions, for example with variables, tables, etc), a name will start with either a letter (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z) or an underscore
  • After the first character, we will use any combination of letters, digits, or underscores
  • A name will not start with two underscores
  • If the name is a combination of words, at least the second word will start in uppercase. Examples are Countries Statistics, Global Survey, _RealSport, FullName, or DriversLicenseNumber
The Name of a Database

After creating an object whose name includes space, whenever you use that object, include its name between [ and ]. Examples are [Countries Statistics], [Global Survey], or [Date of Birth]. Even if you had created an object with a name that doesn't include space, when using that name, you can still include it in square brackets. Examples are [UnitedStations], [FullName], [DriversLicenseNumber], and [Country].

Practical LearningPractical Learning: Starting the Management Studio

  1. All Computers: In the Object Explorer, right-click Databases and click New Database...
     
    New Database
  2. Server: Type MotorVehicleAdministration
  3. pkatts: Type MotorVehicleAdministration1
  4. gmonay: Type MotorVehicleAdministration2
  5. rkouma: Type MotorVehicleAdministration3
  6. operez: Type MotorVehicleAdministration4

The Owner of a Database

Whenever a new database is created, the server wants to keep track of who created that database. This is known as the database owner. By default, Microsoft SQL Server creates a special account named dbo (for database owner). When you create a database but do not specify the owner, this account is used. The dbo account is also given rights to all types of operations that can be performed on the database. This is convenient in most cases. Still, if you want, you can specify another user as the owner of the database. Of course, the account must exist, which means you should have previously created it or you can use an existing one.

To visually specify the owner of a database you are creating, you can click <default> in the Owner text box, type the name of the domain, followed by the back slash, and followed by the user name who will own the database. Alternatively, you can click the ellipsis button on the right side of the Owner text box. This would open the Select Database Owner dialog box:

The Owner of a Database

Select Database Owner

In the Enter the Object Names to Select dialog box, enter the full name or the username of the user to whom you want to assign the database. After doing that, click Check Names. If the name is right, the dialog box would accept it. If the name is not right, you would receive an error. You can click the Browse button. This would open the Browse For Objects dialog box. If you see the user object you want to use, click its check box and click OK.

Practical LearningPractical Learning: Specifying the Database Owner

  • All Computers: In the Owner dialog box, click <default> and type the domain name, followed by \, and followed by your login name (you can also click the browser button on the right side of Owner to locate and select the desired username):
New Database

The Primary Size of a Database

When originally creating a database, you may or may not know how many lists, files, or objects the project would have. Still, as a user of computer memory, the database must use a certain portion, at least in the beginning. The amount of space that a database is using is referred to as its size. If you use the New Database dialog box, after specifying the name of the database and clicking OK, the interpreter automatically specifies that the database would primarily use 2MB. This is enough for a starting database. Of course, you can either change this default later on or you can increase it when necessary.

If you want to specify a size different from the default, if you are using the New Database to create your database, in the Database Files section and under the Initial Size column, change the size as you wish.

Practical LearningPractical Learning: Setting the Database File Size

  • All Computers: In the Database Files section, click the box under the Initial Size column header, click the up arrow of the spin button and increase its value to 5
Initial Size

The Location of a Database

As you should be aware of already from your experience on using computers, every computer file must have a path. The path is where the file is located in one of the drives of the computer. This allows the operating system to know where the file is, so that when you or another application calls it, the operating system would not be confused.

By default, when you create a new database, Microsoft SQL Server assumes that it would be located at Drive:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA folder. If you use the New Database dialog box of the SQL Server Management Studio, if you specify the name of the database and click OK, the interpreter automatically creates a new file, and appends the .MDF extension to the file: this is the (main) primary data file of your database.

If you do not want to use the default path, you can change it. If you are using the New Database dialog box, to change the path, under the Path header, select the current string:

New Database

Replace it with an appropriate path of your choice.

New Database

Practical LearningPractical Learning: Checking the Location of the Data File

  1. All Computers: Scroll to the right side and, under the Path header, notice the location of the file
  2. All Computers: Click OK (all students may receive an error because of rights issues that we will learn before the end of this lesson)

Default Databases

 

Introduction

When you install Microsoft SQL Server, it also installs 4 databases named master, model, msdb, and tempdb. These databases will be for internal use. This means that you should avoid directly using them, unless you know exactly what you are doing.

The System Databases

One of the databases installed with Microsoft SQL Server is named master. This database holds all the information about the server on which your Microsoft SQL Server is installed. For example, you know that, to perform any operation on the server, you must login. The master database identifies any user who accesses the database, when, and how.

Besides identifying who accesses the system, the master database also keeps track of everything you do on the server, including creating and managing databases.

You should not play with the master database at the risk of corrupting the system. For example, if the master database is not functioning right, the system would not work.

Database Creation With Code

 

Introduction

To assist you with creating and managing databases, including their objects, you use a set of language tools referred to as the Data Definition Language (DDL). This language is mostly made of commands. For example, the primary command to create a database uses the following formula:

CREATE DATABASE DatabaseName

To assist you with writing code, in the previous lessons, we saw that you could use the Query window and/or the Template Explorer.

The CREATE DATABASE (remember that SQL is not case-sensitive) expression is required. The DatabaseName factor is the name that the new database will have. Although SQL is not case-sensitive, you should make it a habit to be aware of the cases you use to name your objects.

Every statement in SQL can be terminated with a semi-colon. Although this is a requirement in some implementations of SQL, in Transact-SQL, you can omit the semi-colon. Otherwise, the above formula would be

CREATE DATABASE DatabaseName;
Database Creation With Code

Here is an example:

CREATE DATABASE NationalCensus;

This formula is used if you don't want to provide any option. We saw previously that a database has one or more files and we saw where they are located by defauft. We also saw that you could specify the location of files if you want. To specify where the primary file of the database will be located, use the following formula:

CREATE DATABASE DatabaseName
ON PRIMARY
( NAME = LogicalName, FILENAME = Path )

The only three factors whose values need to be changed from this formula are the database name that we saw already, the logical name, and the path name. The logical name can be any one-word name but should be different from the database name. The path is the directory location of the file. This path ends with a name for the file with the extension .mdf. The path should be complete and included in single-quotes. Here is an example:

CREATE DATABASE NationalCensus
ON PRIMARY
( NAME = DataRepository, FILENAME = 'C:\Exercises\NationalCensus.mdf')
GO

Besides the primary file, you may want to create and store a log file. To specify where the log file of the database would be located, you can use the following formula:

CREATE DATABASE DatabaseName
ON PRIMARY
( NAME = LogicalName, FILENAME = Path.mdf )
LOG ON
( NAME = LogicalName, FILENAME = Path.ldf )

Like the primary file, the log file must be named (with a logical name). The path ends with a file name whose  extension is .ldf. Here is an example:

CREATE DATABASE NationalCensus
ON PRIMARY
( NAME = DataRepository, FILENAME = 'C:\Exercises\NationalCensus.mdf')
LOG ON
( NAME = DataLog, FILENAME = 'C:\Exercises\NationalCensus.ldf')
GO

Practical LearningPractical Learning: Creating a Database Using SQL

  1. All Computers: To open the code editor, in the Object Explorer, right-click the name of the server and click New Query
     
    Microsoft SQL Server Management Studio
  2. All Computers: In the empty window, type:
    CREATE DATABASE RealEstate1;
    GO
  3. All Computers: To execute the statement, press F5 (all students may receive an error because of rights issues that we will learn before the end of this lesson)

Using Code Template

To specify more options with code, Microsoft SQL Server ships with various sample codes you can use for different assignments. For example, you can use sample code to create a database.

The sample codes that Microsoft SQL Server are accessible from the Template Explorer. To access the Template Explorer, on the main menu, you can click View -> Template Explorer.

Before creating a database, open a new Query window. Then:

  • To create a new database using sample code, in the Template Explorer, expand the Databases node, then drag the Create Database node and drop it in the query window. The new database would be created in the server that holds the current connection
  • If you have access to more than one server, to create a database in another server or using a different connection, in the Template Explorer, expand the Databases node, right-click Create Database and click Open. In the Connect to Database Engine dialog box, select the appropriate options, and can click OK
Using Code Template

After any of these actions, Microsoft SQL Server would generate sample code for you:

-- =============================================
-- Create database template
-- =============================================
USE master
GO

-- Drop the database if it already exists
IF  EXISTS (
	SELECT name 
		FROM sys.databases 
		WHERE name = N'<Database_Name, sysname, Database_Name>'
)
DROP DATABASE <Database_Name, sysname, Database_Name>
GO

CREATE DATABASE <Database_Name, sysname, Database_Name>
GO

You would then edit the code and execute it to create the database. From the previous lessons and sections, we have reviewed some characters such as the comments -- and some words or expressions such as GO, CREATE DATABASE, and SELECT. We will study the other words or expressions in future lessons and sections.

Database Routines

 

The Current Database

While writing code in a Query Window, you should always know what database you are working on, otherwise you may add code to the wrong database.

Before visually making a database the current, a Query window must be opened. To visually select a database and make it the current, in the SQL Designer toolbar, click the arrow of the Available Databases combo box and select the desired database:

Available Databases

To programmatically specify the current database, in a Query window or at the Command Prompt (including PowerShell), type the USE keyword followed by the name of the database. The formula to use is:

USE DatabaseName;

Here is an example:

USE GovernmentStatistics;

Refreshing the List of Databases

Some of the windows that display databases, like the SQL Server Management Studio, don't update their list immediately if an operation occurred outside their confinement. For example, if you create a database in a Query window, its name would not be updated in the Object Explorer. To view such external changes, you can refresh the window that holds the list.

In SQL Server Management Studio, to update a list, you can right-click its category in the Object Explorer and click Refresh. For example, to refresh the list of databases, in the Object Explorer, you can right-click the Databases node and click Refresh.

The Users of a Database

 

Introduction to Users

A user of a computer, or a user of an application, simply called a user, is a person who has been given the right to use either the computer or an application. For a person to use Microsoft SQL Server, an account must be created for him or her.

As you may remember, when you install Microsoft SQL Server, you must use an account that has administrative rights. We also mentioned that there is an existing account named sa.

These two accounts allow you to perform the necessary preliminary operations on a Microsoft SQL Server. Obviously, you may need to create other accounts, for the users.

Creating a User

To create a user, you must give a name for the account. The name can be anything. You can even use a name that is not found anywhere in the computer or in the domain. Then, and most importantly, you must specify the login name that will use that user name.

The Users of a Database

This means that you must associate the user name with a login name that was created already.

To visually create a user, in the Object Explorer, expand the database whose user(s) you want to create and expand its Security node. Right-click Users and click New User...

New User

This would open the Database User - New dialog box:

Database User - New

In the User Name, type the name you want. In the Login Name, you must type a valid user name for an existing account. After specifying the login and the user name, you can select other options in the check boxes, options we will ignore at this time. Then click OK.

The formula to programmatically create a user is:

CREATE USER user_name 
    [ { { FOR | FROM }
      { 
        LOGIN login_name 
        | CERTIFICATE cert_name 
        | ASYMMETRIC KEY asym_key_name
      } 
      | WITHOUT LOGIN
    ] 
    [ WITH DEFAULT_SCHEMA =schema_name ]

If you want Microsoft SQL Server to generate code for you, open a new Query window. In the Template Explorer, expand the User node. Drag Create User As DBO and drop it in the text editor:

-- ==============================
-- Create User as DBO template
-- ==============================

USE <database_name, sysname, AdventureWorks>
GO

-- For login <login_name, sysname, login_name>, create a user in the database
CREATE USER <user_name, sysname, user_name>
	FOR LOGIN <login_name, sysname, login_name>
	WITH DEFAULT_SCHEMA = <default_schema, sysname, dbo>
GO

-- Add user to the database owner role
EXEC sp_addrolemember N'db_owner', N'<user_name, sysname, user_name>'
GO

You start with the CREATE USER expression followed by a user name. As mentioned already, it can be almost anything. After the user name, to associate a login to the user, type FOR LOGIN followed by the login name that will use it.

If the name is in one word, simply type it. Here is an example:

CREATE USER JohnYamo
FOR LOGIN rkouma;
GO

If the name is in more than one word, include it in square brackets.  Here is an example:

CREATE USER [Paul Martin Souffrance]
FOR LOGIN rkouma;
GO

The other things are optional.

Practical LearningPractical Learning: Creating Users

  1. Server:
    1. In the Object Explorer, right-click Databases and click Refresh
    2. Click the + button of MotorVehicleAdministration to expand it
    3. Click the + button of Security to expand it
    4. Right-click Users and click New User...
    5. In the User Name, type Orlando Perez
    6. On the right side of the Login Name text box, click the button
    7. In text box, type pkatts
    8. Click Check Names
    9. When the name has been found, click OK
    10. Don't change the other options and click OK
    11. Right-click MotorVehicleAdministration and click Start PowerShell
    12. Type SQLCMD and press Enter
    13. To create another user, type the following and press Enter after each line:
      1> CREATE USER [Gertrude Danielle Monay]
      2> FOR LOGIN gdmonay;
      3> GO
    14. To create a user for a different database, type the following and press Enter after each line:
      1> USE RealEstate1;
      2> GO
      Changed database context to 'RealEstate1'.
      1> CREATE USER Orlando
      2> FOR LOGIN operez;
      3> GO
    15. Return to Microsoft SQL Server Management Studio

Roles

A role is an action or a set of actions that are allowed to a security principal. For example a person A can be allowed to create and use a database. The ability to perform such an action is referred to as a role. Another person B can be allowed only to use an existing database without being able to create a new one. This is another type of role.

 
 
 

Database Maintenance

 

Introduction

If you have created a database but don't need it anymore, you can delete it. It is important to know, regardless of how you create a database, whether using SQL Server Management Studio, code in the query window, or the Command Prompt, every database can be accessed by any of these tools and you can delete any of the databases using any of these tools.

As done with creating a database, every tool provides its own means.

SQL Server Management Studio

To delete a database in SQL Server Management Studio, in the Object Explorer, expand the Databases node, right-click the undesired database, and click Delete. A dialog box would prompt you to confirm your intention. If you still want to delete the database, you can click OK. If you change your mind, you can click Cancel.

Deleting a Database Using SQL

To delete a database in a Query window, use the DROP DATABASE expression followed by the name of the database. The formula used is:

DROP DATABASE DatabaseName;

Before deleting a database in SQL, you must make sure the database is not being used or accessed by someone else or by another object.

Schemas

 

Introduction to Namespaces

A namespace is a group of "things" where each thing has a unique name:

Namespace

Notice that there are various types of objects within a namespace. For example, inside a company, each department has a unique name. Because two companies are independent, they can have departments that have the same name inside each company.

To organize its own items, a namespace can have other namespaces inside. That is, a namespace can have its own sub-namespaces, just like a company can have divisions.

Introduction to Schemas

As mentioned already, a namespace can have objects inside. To further control and manage the objects inside of a namespace, you can put them in sub-groups called schemas. Therefore, a schema (pronounced skima) is a group of objects within a namespace. This also means that, within a namespace, you can have as many schemas as you want:

Notice that, just like a namespace can contain objects (schemas), a schema can contain objects also (the objects we will create throughout our lessons).

To manage the schemas in a namespace, you need a way to identify each schema. Based on this, each schema must have a name. In our illustration, one schema is named Schema1. Another schema is named Schema2. Yet another schema is named Schema_n.

Creating a Schema

A schema is an object that contains other objects. Before using it, you must create it or you can use an existing schema. There are two types of schemas you can use, those built-in and those you create. When Microsoft SQL Server is installed, it also creates a few schemas. One of the schemas is named sys. Another is called dbo.

The sys schema contains a list of some of the objects that exist in your database system. One of these objects is called databases (actually, it's a view). When you create a database, its name is entered in the databases list using the same name you gave it.

To access the schemas of a database, in the Object Explorer, expand the Databases node, expand the database that will hold or own the schema, and expand the Security node.

To visually create a schema, right-click Schemas and click New Schema...

Object Explorer - New Schema

This would open the Schema - New dialog box. In the Schema Name text box, enter a one-word name. Here is an example:

Schema

After providing a name, you can click OK.

The formula to programmatically create a schema is:

CREATE SCHEMA schema_name_clause [ <schema_element> [ ...n ] ]

<schema_name_clause> ::=
    {
    schema_name
    | AUTHORIZATION owner_name
    | schema_name AUTHORIZATION owner_name
    }

<schema_element> ::= 
    { 
        table_definition | view_definition | grant_statement |
        revoke_statement | deny_statement 
    }

The most important part is:

CREATE SCHEMA schema_name_clause [ <schema_element> [ ...n ] ]

In this case, start with the CREATE SCHEMA expression and add a name to it. Here is an example:

1> CREATE SCHEMA PrivateListing;
2> GO
1>

The other parts deal with issues we have not studied yet.

Accessing an Object From a Schema

Inside of a schema, two objects cannot have the same name, but an object in one schema can have the same name as an object in another schema. Based on this, if you are accessing an object within its schema, you can simply use its name, since that name would be unique. On the other hand, because of the implied possibility of dealing with objects with similar names in your server, when accessing an object outside of its schema, you must qualify it. To do this, you would type the name of the schema that contains the object you want to use, followed by the period operator, followed by the name of the object you want to use. From our illustration, to access the Something1 object that belongs to Schema1, you would type:

Schema1.Something1

As mentioned already, when Microsoft SQL Server is installed, it creates a schema named dbo. This is probably the most common schema you will use. In fact, if you don't create a schema in a database, the dbo schema is the default and you can apply it to any object in your database.

Introduction to Rights and Permissions

 

Overview

A permission is an action that a user is allowed to perform, or is prevented from performing, on a database or on one of its objects.

Author Note

Many server operating systems and database environments use the word "right" for permission. In our lessons, we will use both words interchangeably. That is, for the rest of our lessons, the words "right" and "permission" will mean the exact same thing.

Microsoft SQL Server provides various levels of security and therefore permissions are managed on different levels.

First of all, there are two categories of people who use a database: the database developers and the regular users. As a consequence, the are two categories of permissions you will deal with.

Granting a Permission

In order to do something on the server or one of its objects, a user must be given the permission. This is also referred to as granting a permission. To grant permissions, the account you are using must have the ability to do so. This means that, before granting permissions, you must log in with an account that has its own right permissions. You can grant permissions visually or with code.

To visually grant one or more permissions on the server, in the Object Explorer, right-click the name of the server and click Properties. In the left frame of the Server Properties dialog box, click Permissions. In the Logins or Roles list, click the name of the user. In the bottom list, use the options in the Grant column:

Server Properties

The basic formula to programmatically grant one or more permissions is:

GRANT Permission TO Login

You start with the GRANT keyword followed by the name of the permission. After the permission, type TO, followed by the login name you want to grant the permission to. Here is an example that gives operez to create a database on the server:

USE master;
GO
GRANT CREATE ANY DATABASE
TO operez;
GO

If you want to grant more than one permission, separate their names with commas. Here is an example:

GRANT CREATE ANY DATABASE, SHUTDOWN
TO operez;
GO

If you want to grant the same permission(s) to more than one account, list them, separated by commas. Here is an example:

GRANT CREATE ANY DATABASE, ALTER ANY LOGIN
TO pkatts, gdmonay;
GO

Practical LearningPractical Learning: Granting a Permission

  1. Server: In the Object Explorer, right-click the top node (the name of the computer) and click Properties...
  2. Server: In the left frame, click Permissions
  3. Server: In the Logins or Roles list, click DomainName\pkatts
  4. Server: In the Permissions list, in the Grant column, click the check box that corresponds to Create Any Database.
    Still in the Grant column, make sure the check box of Connect SQL is checked
     
    Server Properties
  5. Server: Still in the Permissions for pkatts section, in the Grant column, click the check boxes that correspond to Alter Any Connection, Alter Any Database, and Alter Any Login
     
    Server Properties
  6. Server: In the Logins or Roles list, click DomainName\gmonay
  7. Server: In the Permissions list, in the Grant column, click the check box that corresponds to Create Any Database.
    Make sure the check box of Connect SQL is checked
  8. Server: In the Logins or Roles list, click DomainName\rkouma
  9. Server: In the Permissions list, in the Grant column, click the check box that corresponds to Create Any Database.
    Make sure the check box of Connect SQL is checked
  10. Server: In the Logins or Roles list, click DomainName\operez
  11. Server: In the Permissions list, in the Grant column, click the check box that corresponds to Create Any Database.
    Make sure the check box of Connect SQL is checked
  12. Server: Click OK

Connection to a Server

To primary permission a person needs in Microsoft SQL Server is to be able to connect to the server. This permission is called CONNECT. This is also the default permission. After all, if a person cannot establish a connection to the server, she cannot use the database. When you create a new user account, it is automatically given the right to connect to the server. Otherwise, you can deny it if you want.

Practical LearningPractical Learning: Creating a Database

  1. Each Student: In the Object Explorer, right-click Databases and click New Database...
     
    New Database
  2. pkatts: Type MotorVehicleAdministration1
  3. gmonay: Type MotorVehicleAdministration2
  4. rkouma: Type MotorVehicleAdministration3
  5. operez: Type MotorVehicleAdministration4
  6. Each Student: In the Owner dialog box, click <default> and type the domain name, followed by \, and followed by your login name (you can also click the browser button on the right side of Owner to locate and select the desired username)
  7. Each Student: In the Database Files section, click the box under the Initial Size column header, click the up arrow of the spin button and increase its value to 5
  8. Each Student: Scroll to the right side and, under the Path header, notice the location of the file
  9. Each Student: To open the code editor, in the Object Explorer, right-click the name of the server and click New Query
     
    Microsoft SQL Server Management Studio
  10. Each Student: In the empty window, type:
    CREATE DATABASE RealEstate1;
    GO
  11. Each Student: To execute the statement, press F5

Denying a Permission

As opposed to granting rights, you can prevent a user from doing something on the server, on a database, or on an object. This is referred to as denying a permission.

To visually deny one or more permissions, in the Object Explorer, right-click the name of the server and click Properties. In the left frame, click Permissions. In the Logins or Roles list, click the name of the user. Use the options in the Deny column.

The basic formula to programmatically deny one or more permissions is:

DENY Permission1,Permission2, Permission_n
TO Login1, Login2, Login_n

Here is an example:

DENY CREATE ANY DATABASE
TO rkouma;
GO

Practical LearningPractical Learning: Denying a Permission

  1. Server: In the Object Explorer, right-click the name of the computer and click Properties...
  2. Server: In the left frame, click Permissions
  3. Server: In the Logins or Roles list, click operez
  4. Server: In the Permissions list, in the Deny column, click the check box that corresponds to Create Any Database
     
    Server Properties
  5. Server: Click OK
  6. Server: In the Object Explorer, right-click RealEstate1 and click Properties
  7. Server: In the left frame, click Permissions
  8. Server: In the Users or Roles section, click Orlando
  9. Server: In the Permissions for Orlando section, in the Deny column, click the check box that corresponds to Connect
     
    Server Properties
  10. Server: Click OK
  11. operez: In the Object Explorer, expand the Databases node
  12. operez: Click the + button of MotorVehicleAdministration. Notice that you can expand it
  13. operez: Still in the Object Explorer, click the + button of RealEstate1.
    Notice that you receive an error
     
    Denial of Connection
  14. operez: Click OK on the message box
  15. Server: In the Object Explorer, right-click MotorVehicleAdministration and click Delete
     
    Microsoft SQL Server Management Studio
  16. pkatts: Type MotorVehicleAdministration1
  17. gmonay: Type MotorVehicleAdministration2
  18. rkouma: Type MotorVehicleAdministration3
  19. operez: Type MotorVehicleAdministration4
  20. All Computers: In the Delete Object dialog box, click OK
  21. Server: Return to PowerShell
  22. Server: Type USE Master; and press Enter
  23. Server: Type GO and press Enter
  24. Server: To delete a database, type the following code and press Enter after each line:
    DROP DATABASE RealEstate1;
    GO
    Dropping a Database
  25. Server: Type Quit and press Enter
  26. Server: Type Exit and press Enter
  27. Server: Back in the SQL Server Management Studio, click inside the Query window and press Ctrl + A to select everything
  28. Server: To delete a database, type the following code:
    drop database [beauty salon];
    GO
  29. Server: Press F5 to execute the statement
  30. All computers: Close Microsoft SQL Server
  31. All Computers: When asked whether you want to save, click No

Managing Permissions

There are many issues you need to keep in mind in order to rightfully manage permssions. This is because permissions are somehow interconnected. This means that granting one permission may not work if another right is not given or is denied to the same user.

There are many permissions in Microsoft SQL Server. Some permissions are used regularly and are of primary importance:

  • CONNECT: Obviously the primary right you need to give a user is the ability to connect to a Microsoft SQL Server database. If you want to permanently or temporarily block access of the server to a user, you can deny the Connect permission
  • CREATE ANY DATABASE: By default, users are able to create new databases on the server as long as they have access to it (to the server). The CREATE ANY DATABASE permission allows a user to create a new database. If you want a user to only be able to use existing databases created by other people such as the database administrator(s), you should deny this right
  • ALTER ANY DATABASE: Even if you prevent a user from creating new databases, she can still change something in the existing databases. To prevent such actions, you should deny this right
  • ALTER ANY LOGIN: This permission allows a user (the user who receives this right) to change the login account of another user. This right should be granted only to database administrators

Extending Permissions

Besides granting or denying permissions to an account, you can give an account the ability to grant or deny permissions to other accounts. To do this visually, open the Database Properties for the database you want to work on. In the Users or Roles section, select the user. In the Persmissions, use the check boxes in the With Grant column.

The formula to programmatically give an account the ability to grant or deny permissions to other accounts is:

GRANT Permission1,Permission2, Permission_n
TO Login1, Login2, Login_n
WITH GRANT OPTION

This follows the same formula as the GRANT right we saw earlier. You must just add the WITH GRANT OPTION expression.

Revoking Permissions

Consider the following SQL statement:

DENY CREATE ANY DATABASE
TO rkouma;
GO

When this code has been executed, if the TO user logs in and tries creating a database, he would receive an error:

Error

Revoking a permission consists of either denying a permission that was previously granted or granting a permission that was previously denied. To visually do this, open the Properties dialog box of the database (or the object) on which the permission was managed.

To programmatically revoke a permission, the formula to follow is:

REVOKE [ GRANT OPTION FOR ] <permission> [ ,...n ]  
    { TO | FROM } <database_principal> [ ,...n ] 
        [ CASCADE ]
    [ AS <database_principal> ]

<permission> ::=  permission | ALL [ PRIVILEGES ]

<database_principal> ::= Database_user 
    | Database_role 
    | Application_role 
    | Database_user_mapped_to_Windows_User 
    | Database_user_mapped_to_Windows_Group 
    | Database_user_mapped_to_certificate 
    | Database_user_mapped_to_asymmetric_key 
    | Database_user_with_no_login

Start with the REVOKE keyword followed by the permission(s). This is followed by either TO or FROM and the login name of the account whose permission must be managed. Here is an example:

/*
DENY CREATE ANY DATABASE
TO rkouma;
GO
*/

REVOKE CREATE ANY DATABASE
TO rkouma;
GO

Revoking a permission doesn't give that same permission. Imagine a user with a newly created account didn't have the permission to create new databases. If you deny that person the ability to create new databases, that denial becomes effective. If you revoke the permission, you are asking the server to restore the status of that person with regards to that particular right. That doesn't give that user the permission. The above code doesn't give the user the right to create new databases. If you want the user to have a right, you must explicitly grant the permission. Consider the following code:

REVOKE CREATE ANY DATABASE
TO rkouma;
GO

GRANT CREATE ANY DATABASE
TO rkouma;
GO

This restores the user's denial for creating new databases, then grants the permission to that user. This time, the user has the right to create new databases.

Exercises

   

National Health Care Management

  1. On the C:\ drive or any drive on the computer, create a folder named National Health Care Management
  2. Using PowerShell, create a database named nhcm1 (which stands for National Health Care Management 1). Store its .mdf and its .ldf files in the National Health Care Management directory

Metropolitan Area Electric Company

  • Start Microsoft SQL Server and login
  • By writing SQL code in a Query window, create a database named MetrEC (this stands for Metropolitan Area Electric Company)
 
 
   
 

Previous Copyright © 2007-2012 Fianga.com Next