Lession 3 introduction to database

918 views
793 views

Published on

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
918
On SlideShare
0
From Embeds
0
Number of Embeds
494
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Lession 3 introduction to database

  1. 1. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn51Lession 3: Introduction to DatabaseIntroduction to Database CreationOverviewA 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 aredifferent ways to create a database.To visually create a new database in Microsoft SQL Server Management Studio, in theObject Explorer, you can right-click the Databases node and click New Database... Thiswould open the New Database dialog box.Practical Learning: Introducing Databases1. Start Microsoft SQL Server2. In the Authentication combo box, select Windows Authentication and make sure theAdministrator account is selected in the User Name (or the account you used whenyou installed Microsoft SQL Server)3. Click ConnectThe Name of a DatabaseProbably the most important requirement of creating a database is to give it a name. TheSQL is very flexible when it comes to names. In fact, it is very less restrictive than mostother computer languages. Still, there are rules you must follow when naming the objectsin your databases: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,
  2. 2. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn52Y, or Z), a digit (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), an underscore (_) or a non-readablecharacter. Examples are _n, act, %783, SecondAfter the first character (letter, digit, underscore, or symbol), the name can havecombinations of underscores, letters, digits, or symbols. Examplesare _n24 or act_52_tA name can include spaces. Example are c0untries st@ts, govmnt (records),or gl0b# $urvey||Because of the flexibility of SQL, it can be difficult to maintain names in a database. Basedon this, there are conventions we will use for our objects. In fact, we will adopt the rulesused 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 underscoreAfter the first character, we will use any combination of letters, digits, orunderscoresA name will not start with two underscoresIf the name is a combination of words, at least the second word will start inuppercase. Examples are Countries Statistics, GlobalSurvey, _RealSport, FullName, or DriversLicenseNumberAfter creating an object whose name includes space, whenever you use that object,include its name between [ and ]. Examples are [Countries Statistics], [GlobalSurvey], or [Date of Birth]. Even if you had created an object with a name that doesntinclude space, when using that name, you can still include it in square brackets. Examplesare[UnitedStations], [FullName], [DriversLicenseNumber], and [Country].
  3. 3. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn53Practical Learning: Starting the Management Studio1. In the Object Explorer, right-click Databases and click New Database...2. In the Name text box, type MotorVehicleAdministrationThe Owner of a DatabaseWhenever a new database is created, the server wants to keep track of who created thatdatabase. This is known as the database owner. By default, Microsoft SQL Server createsa special account named dbo (for database owner). When you create a database but donot specify the owner, this account is used. The dbo account is also given rights to alltypes of operations that can be performed on the database. This is convenient in mostcases. Still, if you want, you can specify another user as the owner of the database. Of
  4. 4. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn54course, the account must exist, which means you should have previously created it or youcan use an existing one.To visually specify the owner of a database you are creating, you can click <default> inthe Owner text box, type the name of the domain, followed by the back slash, andfollowed by the user name who will own the database. Alternatively, you can click theellipsis button on the right side of the Owner text box. This would open the SelectDatabase Owner dialog box:In the Enter the Object Names to Select dialog box, enter the full name or the usernameof the user to whom you want to assign the database. After doing that, click CheckNames. If the name is right, the dialog box would accept it. If the name is not right, youwould receive an error. You can click the Browse button. This would open the Browse ForObjects dialog box. If you see the user object you want to use, click its check box andclick OK.Practical Learning: Specifying the Database OwnerIn the Owner dialog box, click <default> and type DomainNamepkatts (replaceDomainName with the name of your domain; otherwise, skip this step) (you can alsoclick the browser button on the right side of Owner to locate and select the desiredusername)
  5. 5. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn55The Primary Size of a DatabaseWhen originally creating a database, you may or may not know how many lists, files, orobjects the project would have. Still, as a user of computer memory, the database mustuse a certain portion, at least in the beginning. The amount of space that a database isusing is referred to as its size. If you use the New Database dialog box, after specifyingthe name of the database and clicking OK, the interpreter automatically specifies that thedatabase would primarily use 2MB. This is enough for a starting database. Of course, youcan 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 Databaseto create your database, in the Database Files section and under the Initial Size column,change the size as you wish.Practical Learning: Setting the Database File SizeIn 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
  6. 6. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn56The Location of a DatabaseAs you should be aware of already from your experience on using computers, everycomputer file must have a path. The path is where the file is located in one of the drivesof the computer. This allows the operating system to know where the file is, so that whenyou 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 wouldbe located at Drive:Program FilesMicrosoft SQLServerMSSQL10.MSSQLSERVERMSSQLDATA folder. If you use the New Database dialogbox of the SQL Server Management Studio, if you specify the name of the database andclick OK, the interpreter automatically creates a new file, and appends the .MDF extensionto 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 NewDatabase dialog box, to change the path, under the Path header, select the current string:
  7. 7. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn57Replace it with an appropriate path of your choice.Practical Learning: Checking the Location of the Data File1. Scroll to the right side and, under the Path header, notice the location of the file2. Start Windows Explorer3. In the left frame, click the C: drive
  8. 8. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn584. Right-click a blank area in the right frame -> New -> Folder5. Type Microsoft SQL Server Database Development as the name of the newfolder6. Return to the New Database dialog box.Under Path, click the browse button7. Locate the Microsoft SQL Server Database Development folder you created andselect it8. Do the same for the other path9. Click OK
  9. 9. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn59Default DatabasesIntroductionWhen you install Microsoft SQL Server, it also installs 4 databasesnamed 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 youare doing.The System DatabasesOne of the databases installed with Microsoft SQL Server is named master. This databaseholds all the information about the server on which your MS SQL Server is installed. Forexample, We know that, to perform any operation on the server, you must login. Themaster database identifies any person, called a user, who accesses the database, aboutwhen and how.Besides identifying who accesses the system, the master database also keeps track ofeverything you do on the server, including creating and managing databases.You should not play with the master database; otherwise you may corrupt the system. Forexample, if the master database is not functioning right, the system would not work.Database Creation With CodeIntroductionTo assist you with creating and managing databases, including their objects, you use a setof language tools referred to as the Data Definition Language (DDL). This most includescommands. For example, the primary command to create a database uses the followingformula:CREATE DATABASE DatabaseNameTo assist you with writing code, in the previous lessons, we saw that you could use thequery window.The CREATE DATABASE (remember that SQL is not case-sensitive) expression isrequired. 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 casesyou use to name your objects. Every statement in SQL can be terminated with a semi-colon. Although this is a requirement in many implementations of SQL, in Microsoft SQLServer, you can omit the semi-colon. Otherwise, the above formula would beCREATE DATABASE DatabaseName;Here is an example:CREATE DATABASE NationalCensus;This formula is used if you do not want to provide any option. We saw previously that adatabase has one or more files and we saw where they are located by defauft. We alsosaw that you could specify the location of files if you want. To specify where the primaryfile of the database will be located, you can use the following formula:CREATE DATABASE DatabaseNameON PRIMARY( NAME = LogicalName, FILENAME = Path )
  10. 10. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn60The only three factors whose values need to be changed from this formula are thedatabase name that we saw already, the logical name, and the path name. The logicalname can be any one-word name but should be different from the database name. Thepath is the directory location of the file. This path ends with a name for the file with theextension .mdf. The path should be complete and included in single-quotes. Here is anexample:CREATE DATABASE NationalCensusON PRIMARY( NAME = DataRepository, FILENAME = C:ExercisesNationalCensus.mdf)GOBesides the primary file, you may want to create and store a log file. To specify where thelog file of the database would be located, you can use the following formula:CREATE DATABASE DatabaseNameON PRIMARY( NAME = LogicalName, FILENAME = Path.mdf )LOG ON( NAME = LogicalName, FILENAME = Path.ldf )The new factor in this formula is the path of the log file. Like the primary file, the log filemust be named (with a logical name). The path ends with a file name whose extension is.ldf. Here is an example:CREATE DATABASE NationalCensusON PRIMARY( NAME = DataRepository, FILENAME = C:ExercisesNationalCensus.mdf)LOG ON( NAME = DataLog, FILENAME = C:ExercisesNationalCensus.ldf)GOPractical Learning: Creating a Database Using SQL1. To open the code editor, in the Object Explorer, right-click the name of the serverand click New Query2. In the empty window, type:3. CREATE DATABASE RealEstate1
  11. 11. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn614. ON PRIMARY5. ( NAME = DataRepository, FILENAME = C:Microsoft SQL Server DatabaseDevelopmentRealEstate1.mdf)6. LOG ON7. ( NAME = DataLog, FILENAME = C:Microsoft SQL Server DatabaseDevelopmentRealEstate1.ldf)GO8. To execute the statement, press F5Using Code TemplateTo specify more options with code, Microsoft SQL Server ships with various sample codesyou can use for different assignments. For example, you can use sample code to create adatabase. The sample codes that Microsoft SQL Server are accessible from the TemplateExplorer.To access the Template Explorer, on the main menu, you can click View -> TemplateExplorer. Before creating a database, open a new query window. Then:To create a new database using sample code, in the Template Explorer, expand theDatabases node, then drag the Create Database node and drop it in the querywindow. The new database would be created in the server that holds the currentconnectionIf you have access to more than one server, to create a database in another serveror using a different connection, in the Template Explorer, expand the Databasesnode, right-click Create Database and click Open. In the Connect to Database Enginedialog box, select the appropriate options, and can click OKWith any of these actions, Microsoft SQL Server would generate sample code for you:-- =============================================-- Create database template-- =============================================USE masterGO-- Drop the database if it already existsIF EXISTS (SELECT nameFROM sys.databasesWHERE name = N<Database_Name, sysname, Database_Name>)
  12. 12. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn62DROP DATABASE <Database_Name, sysname, Database_Name>GOCREATE DATABASE <Database_Name, sysname, Database_Name>GOYou would then need to edit the code and execute it to create the database. From theprevious lessons and sections, we have reviewed some characters uch as the comments --and some words or expressions such as GO, CREATE DATABASE, and SELECT. We willstudy the other words or expressions in future lessons and sections.The Users of a DatabaseIntroduction to UsersA user of a computer, or a user of an application, simply called a user, is a person whohas been given the right to use either the computer or an application. For a person to useMicrosoft 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 administrativerights. We also mentioned that there is an existing account named sa. These two accountsallow you to perform the necessary preliminary actions on a Microsoft SQL Server.Obviously, you may need to create other accounts, for the users.Creating a UserTo create a user, you must give a name for the account. The name can be anything. Youcan even use a name that is not found anywhere in the computer or the domain. Then,and most importantly, you must specify the login name that will use that user name. Thismeans that you must associate the user name with a login name that was createdalready.To visually create a user, in the Object Explorer, expand the database whose user(s) youwant to create and expand its Security node. Right-click Users and click New User... Thiswould open the Database User - New dialog box. In the User Name, type the name youwant. In the Login Name, you must type a valid user name for an existing account. Afterspecifying the login and the user names, 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. Inthe Template Explorer, expand the User node. Drag Create User As DBO and drop it in thetext editor:-- ==============================-- Create User as DBO template-- ==============================
  13. 13. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn63USE <database_name, sysname, AdventureWorks>GO-- For login <login_name, sysname, login_name>, create a user in the databaseCREATE 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 roleEXEC sp_addrolemember Ndb_owner, N<user_name, sysname, user_name>GOYou start with the CREATE USER expression followed by a user name. As mentionedalready, 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 JohnYamoFOR LOGIN rkouma;GOIf 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;GOThe other things are optional.Practical Learning: Creating Users1. In the Object Explorer, right-click Databases and click Refresh2. Click the + button of MotorVehicleAdministration to expand it3. Click the + button of Security to expand it4. Right-click Users and click New User...5. In the User Name, type Orlando Perez6. On the right side of the Login Name text box, click the button7. In text box, type pkatts8. Click Check Names9. When the name has been found, click OK10.Dont change the other options and click OK11.Right-click MotorVehicleAdministration and click New Query12.To create another user, type the following:13. CREATE USER [Gertrude Danielle Monay]14. FOR LOGIN gdmonay;GO15.To execute, press F516.Click inside the Query window and press Ctrl + A17.To create a user for a different database, type the following:18. USE RealEstate1;
  14. 14. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn6419. GO20. CREATE USER Orlando21. FOR LOGIN operez;GO22.Press F5 to executeRolesA role is an action or a set of actions that are allowed to a security principal. For examplea person A can be allowed to create and use a database. The ability to perform such anaction is referred to as a role. Another person B can be allowed only to use an existingdatabase without being able to create a new one. This is another type of role.Database MaintenanceIntroductionIf you have created a database but dont need it anymore, you can delete it. It isimportant to know, regardless of how you create a database, whether using SQL ServerManagement Studio, code in the query window, or the Command Prompt, every databasecan be accessed by any of these tools and you can delete any of the databases using anyof these tools.As done with creating a database, every tool provides its own means.SQL Server Management StudioTo delete a database in SQL Server Management Studio, in the Object Explorer, expandthe Databases node, right-click the undesired database, and click Delete. A dialog boxwould prompt you to confirm your intention. If you still want to delete the database, youcan click OK. If you change your mind, you can click Cancel.Deleting a Database Using SQLTo delete a database in SQL Query Analyzer, you use the DROP DATABASE expressionfollowed 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 oraccessed by some one else or by another object.Database RoutinesThe Current DatabaseWhile writing code in a Query Window, you should always know what database you areworking on, otherwise you may add code to the wrong database. To programmaticallyspecify the current database, type the USEkeyword followed by the name of thedatabase. The formula to use is:USE DatabaseName;Here is an example:USE GovernmentStatistics;
  15. 15. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn65Refreshing the List of DatabasesSome of the windows that display databases, like the SQL Server Management Studio,dont update their list immediately if an operation occurred outside their confinement. Forexample, if you create a database in the query windows, its name would not be updatedin the Object Explorer. To view such external changes, you can refresh the window thatholds the list.In SQL Server Management Studio, to update a list, you can right-click its category in theObject Explorer and click Refresh. Only that category may be refreshed. For example, torefresh the list of databases, in the Object Explorer, you can right-click the Databasesnode and click Refresh.SchemasIntroduction to NamespacesA namespace is a technique of creating a series of items that each has a unique name. Forexample, if you start creating many databases, there is a possibility that you may riskhaving various databases with the same name. If using a namespace, you can isolate thedatabases in various namespaces. In reality, to manage many other aspects of yourdatabase server, you use namespaces and you put objects, other than databases, withinthose namespaces. Therefore, a namespace and its content can be illustrated as follows:Notice that there are various types of objects within a namespace.Introduction to SchemasWithin a namespace, you can create objects as you wish. To further control and managethe objects inside of a namespace, you can put them in sub-groups called schemas.Therefore, a schema is a group of objects within a namespace. This also means that,within a namespace, you can have as many schemas as you want:
  16. 16. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn66Notice that, just like a namespace can contain objects (schemas), a schema can containobjects also (the objects we will create throughout our lessons).To manage the schemas in a namespace, you need a way to identify each schema. Basedon this, each schema must have a name. In our illustration, one schema is namedSchema1. Another schema is named Schema2. Yet another schema is named Schema_n.A schema is an object that contains other objects. Before using it, you must create it oryou 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 fewschemas. One of the schemas is called sys.The sys schema contains a list of some of the objects that exist in your system. One ofthese objects is called databases (actually, its a view). When you create a database, itsname is entered in the databasesobject 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.Creating a SchemaTo create a schema, right-click Schemas and click New Schema...
  17. 17. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn67This would open the Schema - New dialog box. In the Schema Name text box, enter aone-word name. Here is an example:After providing a name, you can click OK.
  18. 18. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn68We will see a practical example of creating a schema in Lesson 7.Accessing an Object From a SchemaInside of a schema, two objects cannot have the same name, but an object in one schemacan have the same name as an object in another schema. Based on this, if you areaccessing an object within its schema, you can simply use its name, since that namewould be unique. On the other hand, because of the implied possibility of dealing withobjects with similar names in your server, when accessing an object outside of itsschema, you must qualify it. To do this, you would type the name of the schema thatcontains the object you want to use, followed by the period operator, followed by thename of the object you want to use. From our illustration, to access the Something1object that belongs to Schema1, you would type:Schema1.Something1Introduction to Rights and PermissionsOverviewA permission is an action that a user is allowed to perform, or is prevented fromperforming, on a database or on one of its objects.Many server operating systems and database environments use the word "right" for permissionlessons, we will use both words interchangeably. That is, for the rest of our lessons, the wordand "permission" will mean the exact same thing.Microsoft SQL Server provides two first broad categories of permissions: physical andvirtual. The physical permission has to do with who has physical access to the computeror the room where it is located (who can open it, who can shut it down, etc). We are notconcerned with physical permissions in these lessons. For the rest of our lessons, thepermissions have to do with how to electronically connect to the server and what a usercan do with it.Microsoft SQL Server provides various levels of security and therefore permissions aremanaged on different levels.Granting a PermissionIn order to do something on the server or one of its objects, a user must be given thepermission. This is also referred to as granting a permission. To grant permissions, theaccount you are using must have the ability to do so. This means that, before grantingpermissions, you must log in with an account that has its own right permissions. You cangrant permissions visually or with code.To visually grant one or more permissions on the server, in the Object Explorer, right-clickthe name of the server and click Properties. In the left frame of the Server Propertiesdialog box, click Permissions. In the Logins or Roles list, click the name of the user. In thebottom list, use the options in the Grant column:
  19. 19. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn69The basic formula to programmatically grant one or more permissions on a server is:GRANT Permission TO LoginYou start with the GRANT keyword followed by the name of the permission. After thepermission, type TO, followed by the login name you want to grant the permission to.Here is an example:USE master;GOGRANT CREATE ANY DATABASETO operez;GOIf you want to grant more than one permission, separate their names with commas. Hereis an example:GRANT CREATE ANY DATABASE, SHUTDOWNTO operez;GOIf 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 LOGINTO pkatts, gdmonay;GO
  20. 20. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn70Practical Learning: Granting a Permission1. In the Object Explorer, right-click the top node (the name of the computer) and clickProperties...2. In the left frame, click Permissions3. In the Logins or Roles list, click pkatts4. In the Permissions list, in the Grant column, click the check box that corresponds toCreate Any Database.Make sure Connect SQL is selected5. Still in the Permissions for pkatts section, in the Grant column, click the check boxesthat correspond to Alter Any Connection, Alter Any Database, and Alter Any Login
  21. 21. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn716. Click OK7. On the task bar, click Start -> Switch User8. Log in with the pkatts account9. On the task bar, click Start -> (All) Programs -> Microsoft SQL Server -> SQL ServerManagement Studio10.Make sure the Authentication is set to Windows Authentication and that the pkattsaccount is selected as as the User Name.Click Connect11.In the Object Explorer, expand the Databases node12.Right-click Databases and click New Database...13.In the Name, type Beauty Salon and click OK.Notice that the database has been created.14.On the task bar, click Start -> Log off15.Re-log in as the account you were using beforeConnection to a ServerTo primary permission a person needs in Microsoft SQL Server is to be able to connect tothe server. This permission is called CONNECT. This is also the default permission. Afterall, if a person cannot establish a connection to the server, whats the point? When youcreate a new user account, it is automatically given the right to connect to the server.Otherwise, you can deny it if you want.
  22. 22. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn72Denying a PermissionAs opposed to granting rights, you can prevent a user from doing something on theserver, on a database, or on an object. This is referred to as denying a permission.To visually deny one or more permissions on the server, in the Object Explorer, right-clickthe name of the server and click Properties. In the left frame, click Permissions. In theLogins 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 on a server is:DENY Permission1,Permission2, Permission_nTO Login1, Login2, Login_nHere is an example:DENY CREATE ANY DATABASETO rkouma;GOPractical Learning: Denying a Permission1. In the Object Explorer, right-click the name of the computer and click Properties...2. In the left frame, click Permissions3. In the Logins or Roles list, click operez4. In the Permissions list, in the Deny column, click the check box that corresponds toCreate Any Database5. Click OK
  23. 23. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn736. In the Object Explorer, right-click RealEstate1 and click Properties7. In the left frame, click Permissions8. In the Users or Roles section, click Orlando9. In the Permissions for Orlando section, in the Deny column, click the check box thatcorresponds to Connect10.Click OK11.On the task bar, click Start -> (All) Programs -> Microsoft SQL Server -> SQL ServerManagement Studio12.Set the Authentication to SQL Server Authentication13.In the Login name, type operez and press Tab14.In the password, type P@ssword115.Click Connect16.In the Object Explorer, expand the Databases node17.Click the + button of MotorVehicleAdministration. Notice that you can expand it18.Still in the Object Explorer, click the + button of RealEstate1.Notice that you receive an error
  24. 24. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn7419.Click OK on the message box20.Close Microsoft SQL Server21.Restart it and login with an account that has administrative rights using the WindowsAuthentication22.Click Connect23.In the Object Explorer, right-click MotorVehicleAdministration and click Delete24.In the Delete Object dialog box, click OK25.On the Standard toolbar, click the New Query button26.To delete a database, type:27. DROP DATABASE RealEstate1;28. GO29. drop database [beauty salon];GO
  25. 25. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn7530.Press F5 to execute the statement31.Close Microsoft SQL Server32.When asked whether you want to save, click NoManaging PermissionsThere are many issues you need to keep in mind in order to rightfully managepermssions. This is because permissions are somehow interconnected. This means thatgranting one permission may not work if another right is not given or is denied to thesame user.There are many permissions in Microsoft SQL Server. Some permissions are usedregularly and are of primary importance:CONNECT: Obviously the primary right you need to give a user is the ability toconnect to a Microsoft SQL Server database. If you want to permanently ortemporarily block access of the server to a user, you can deny the ConnectpermissionCREATE ANY DATABASE: By default, users are able to create new databases onthe server as long as they have access to it. The CREATE ANYDATABASE permission allows a user to create a new database. If you want a user toonly be able to use existing databases created by other people such as the databaseadministrator(s), you should deny this rightALTER ANY DATABASE: Even if you prevent a user from creating new databases,he can still change something in the existing databases. To prevent such actions, youshould deny this rightALTER 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 todatabase administratorsExtending PermissionsBesides granting or denying permissions to an account, you can give an account theability to grant or deny permissions to other accounts. To do this visually, open theDatabase 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 permissionsto other accounts is:GRANT Permission1,Permission2, Permission_nTO Login1, Login2, Login_nWITH GRANT OPTIONThis follows the same formula as the GRANT we saw earlier. You must just add the WITHGRANT OPTIONexpression.Revoking PermissionsConsider the following SQL statement:DENY CREATE ANY DATABASETO rkouma;GOWhen this code has been executed, if the TO user logs in and tries creating a database, hewould receive an error:
  26. 26. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn76Revoking a permission consists of either denying a permission that was previously grantedor granting a permission that was previously denied. To visually do this, open theProperties dialog box of the database (or the object) on which the permission wasmanaged.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_loginStart with the REVOKE keyword followed by the permission(s). This is followed byeither TO or FROM and the login name of the account whose permission must bemanaged. Here is an example:/*DENY CREATE ANY DATABASETO rkouma;GO*/REVOKE CREATE ANY DATABASETO rkouma;GORevoking a permission doesnt give that same permission. Imagine a user with a newlycreated account didnt have the permission to create new databases. If you deny thatperson the ability to create new databases, that denial becomes effective. If you revokethe permission, you are asking the server to restore the status of that person with regardsto that particular right. That doesnt give that user the permission. The above codedoesnt give the user the right to create new databases. If you want the user to have aright, you must explicitly grant the permission. Consider the following code:REVOKE CREATE ANY DATABASETO rkouma;GO
  27. 27. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn77GRANT CREATE ANY DATABASETO rkouma;GOThis restores the users denial for creating new databases, then grants the permission tothat user. This time, the user has the right to create new databases.ExercisesNational Health Care ManagementCreate a database named nhcm1 (which stands for National Health CareManagement 1). Accept the default locationMetropolitan Area Electric CompanyBy writing SQL code in a Query window, create a database named MetrEC (thisstands for Metropolitan Area Electric Company)

×