Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Lession 7 records maintenance


Published on

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

Lession 7 records maintenance

  1. 1. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : 7: Records MaintenanceData Import/ExportData ImportOne of the techniques used to get data into one or more tables consists of importing alreadyexisting data from another database or from any other recognizable data file. Microsoft SQLServer provides various techniques and means of importing data.The easiest type of data that can be imported into SQL Server, and which is available on almostall database environments, is the text file. Almost every database environment allows you toimport a text file but data from that file must be formatted appropriately. For example, theinformation stored in the file must define the columns as distinguishable by a character thatserves as a separator. This separator can be the single-quote, the double-quote, or any validcharacter. Data between the quotes is considered as belonging to a distinct field. Besides thisinformation, the database would need to separate information from two different columns. Again,a valid character must be used. Most databases, including Microsoft SQL Server, recognize thecomma as such a character. The last piece of information the file must provide is to distinguisheach record from another. This is easily taken car of by the end of line of a record. This is alsorecognized as the carriage return.These directives can help you manually create a text file that can be imported into Microsoft SQLServer. In practicality, if you want to import data that resides on another database, you can askthat application to create the source of data. Most applications can do that and format the data.That is the case for the data we will use in the next exercise: it is data that resided on a MicrosoftAccess database and was prepared to be imported in Microsoft SQL Server.After importing data, you should verify and possibly format it to customize its fields.Practical Learning: Importing Data From an External Source1. Download the Students text file and save it to your hard drive2. In the SQL Server Management Studio, right-click the Databases node and click NewDatabase...3. Type ROSH and press Enter4. In the Object Explorer, right-click ROSH, position the mouse on Tasks and click ImportData5. On the first page of the wizard, click Next6. On the second page, click the arrow of the Data Source combo box and select Flat FileSource7. On the right side of File Name, click the Browse button8. Locate and select the Students.txt file you had saved9. On the left side, click Columns10.On the left side, click Advanced11.As Column 0 is selected, in the right list, click Name and type StudentID12.Click DataType and click the arrow of its combo box. Select Two-byte unsigned integer[DT_UI2]
  2. 2. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : the middle list, click each column and change its Name in the right column as follows:Name DataType OutputColumnWidthStudentID Two-byte unsigned integer [DT_UI2]FirstName Unicode string [DT_WSTR] 20LastName Unicode string [DT_WSTR] 20DateOfBirth database date [DT_DBDATE]Gender Unicode string [DT_WSTR] 12Address Unicode string [DT_WSTR]City Unicode string [DT_WSTR] 40State Unicode string [DT_WSTR] 2ZIPCode Unicode string [DT_WSTR] 12HomePhone Unicode string [DT_WSTR] 16EmailAddress Unicode string [DT_WSTR]ParentsNames Unicode string [DT_WSTR]SPHome Boolean [DT_BOOL]EmrgName Unicode string [DT_WSTR]EmrgPhone Unicode string [DT_WSTR] 1614.To see the list of columns, under Data Source, click Columns15.Click Next 3 times:
  3. 3. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : Next twice17.Click Finish
  4. 4. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : CloseRecord Maintenance: Updating RecordsIntroductionRecord maintenance includes viewing records, looking for one or more records, modifying one ormore records, or deleting one or more records. These operations can be performed visually orprogrammatically using a Data Definition Language (DDL) command.Practical Learning: Introducing Record Maintenance1. On the Standard toolbar, click the New Query button2. To create a database, type the following:USE master;GOIF EXISTS(SELECT nameFROM sys.databasesWHERE name = NCeilInn2)DROP DATABASE CeilInn2GO
  5. 5. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : DATABASE CeilInn2GOUSE CeilInn2;GOCREATE TABLE Rooms (RoomID int identity(1, 1) NOT NULL,RoomNumber nvarchar(10),RoomType nvarchar(20) default NBedroom,BedType nvarchar(40) default NQueen,Rate money default 75.85,Available bit default 0);GOINSERT INTO Rooms(RoomNumber) VALUES(104);GOINSERT INTO Rooms(RoomNumber, BedType, Rate, Available)VALUES(105, NKing, 85.75, 1),(106, NKing, 85.75, 1);GOINSERT INTO Rooms(RoomNumber, Available) VALUES(107, 1);GOINSERT INTO Rooms(RoomNumber, BedType, Rate)VALUES(108, NKing, 85.75);GOINSERT INTO Rooms(RoomNumber, Available) VALUES(109, 1);GOINSERT INTO Rooms(RoomNumber, RoomType, Rate, BedType, Available)VALUES(110, NConference, 450.00, N, 1);GO3. Press F5 to executeVisually Selecting RecordsBefore visually performing some operations on a table, you must first select one or morerecords. In the Table window, to select one record, position the mouse on the left button of therecord and click:To select a range of records, click the gray button of one of the records, press and hold Shift,then click the gray button of the record at the other extreme.
  6. 6. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : select the records in a random fashion, select one record, press and hold Ctrl, then click thegray button of each desired record:To select all records of a table, click the gray button on the left of the first column:To visually modify one or more records on a table, first open it (you right-click the table in theObject Explorer and click Open Table) to view its records. Locate the record and the field youwant to work on and perform the desired operation.Updating all RecordsUpdating a record consists of changing its value for a particular column. To visually update arecord, in the Object Explorer, right-click its table (or view, in some cases) and click Edit Top200 Rows. This would open the table as a spreadsheet, as seen above. Locate the value underthe desired column header, and modify the value as you see fit.To programmatically update a record, you use a Data Definition Language (DDL) command. Ifyou are working in Microsoft SQL Server:In the Object Explorer, you can right the table, position the mouse on Script Table As ->UPDATE To -> New Query Editor WindowOpen an empty query window and type your codeThe DDL command to update a record is UPDATE. The basic formula to use is:UPDATE TableNameSET ColumnName = ExpressionWith this formula, you must specify the name of the involved table as the TableName factor ofour formula. The SET statement allows you to specify a new value, Expression, for the fieldunder the ColumnName column.Consider the following code to create a new database named VideoCollection and to add a tablenamed Videos to it:CREATE DATABASE VideoCollection;
  7. 7. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : VideoCollection;GOCREATE TABLE Videos (VideoID INT NOT NULL IDENTITY(1,1),VideoTitle nvarchar(120) NOT NULL,Director nvarchar(100) NULL,YearReleased SMALLINT,VideoLength nvarchar(30) NULL,Rating nchar(6));GOINSERT INTO Videos(VideoTitle, Director, YearReleased, VideoLength)VALUES(NA Few Good Men,Rob Reiner,1992,138 Minutes);INSERT INTO Videos(VideoTitle, Director, VideoLength)VALUES(NThe Lady Killers, NJoel Coen & Ethan Coen, N104 Minutes);INSERT INTO Videos(VideoTitle, Director, YearReleased, VideoLength)VALUES(NThe Silence of the Lambs,Jonathan Demme,1991,118 Minutes);INSERT INTO Videos(VideoTitle, Director, VideoLength)VALUES(NThe Distinguished Gentleman, NJames Groeling, N112 Minutes);INSERT INTO Videos(VideoTitle, Director, VideoLength)VALUES(NGhosts of Mississippi, NRob Reiner, N130 Minutes);GOImagine you want to indicate that all these videos are rated R. To do this, in our formula, specifythe table name. In the SET expression, specify the column name as Rating and assign it R as astring. This would be done as follows:USE VideoCollection;GOUPDATE VideosSET Rating = NR;GOIf you use the UPDATE statement like this, it acts on all records. The above code wouldproduce:Record Maintenance: Editing RecordsIntroductionEditing a record consists of changing a value in a field. It could be that the field is empty, suchas the © Year of the the The Lady Killers video of the following table. It could be that the value
  8. 8. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : wrong, such as the Director of the the The Distinguished Gentleman video of this table:Video Title Director © Year Length RatingA Few Good Men Rob Reiner 1992 138 Minutes RThe Silence of the Lambs Jonathan Demme 1991 118 MinutesThe Distinguished Gentleman James Groeling 112 Minutes RThe Lady Killers Joel Coen & Ethan Coen 104 Minutes RGhosts of Mississippi Rob Reiner 130 MinutesEditing a RecordTo edit a record, first open the table to view its records. Locate the record, the column on whichyou want to work, and locate the value you want to change, then change it.To edit a record, you must provide a way for the interpreter to locate the record. To do this, youwould associate the WHERE operator in an UPDATE statement using the following formula:UPDATE TableNameSET ColumnName = ExpressionWHERE Condition(s)The WHERE operator allows you to specify how the particular record involved would beidentified. It is very important, in most cases, that the criterion used be able to uniquely identifythe record. In the above table, imagine that you ask the interpreter to change the released yearto 1996 where the director of the video is Rob Reiner. The UPDATE statement would be writtenas follows:UPDATE VideosSET YearReleased = 1996WHERE Director = NRob Reiner;In the above table, there are at least two videos directed by Rob Reiner. When this statement isexecuted, all video records whose director is Rob Reiner would be changed, which wouldcompromise existing records that didnt need this change. This is where the identity columnbecomes valuable. We saw earlier that, when using it with the IDENTITYfeature, the interpreterappends a unique value to each record. You can then use that value to identify a particularrecord because you are certain the value is unique.Here is an example used to specify the missing copyright year of a particular record:UPDATE VideosSET YearReleased = 1996WHERE VideoID = 5;GOHere is an example used to change the name of the director of a particular video:UPDATE VideosSET Director = NJonathan LynnWHERE VideoTitle = NThe Distinguished Gentleman;Practical Learning: Editing a Record1. Press Ctrl + A to select everything (the code) in the window and, to update a record, typethe following:USE CeilInn2;GO
  9. 9. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : RoomsSET BedType = NQueenWHERE RoomNumber = 108;GO2. Press F5 to execute3. Press Ctrl + A to select the code in the window and type the following:USE CeilInn2;GOUPDATE RoomsSET Available = 0WHERE RoomNumber = 109;GO4. Press F5 to executeOutputting the UpdateAfter making changes to a table using SQL, you dont get a visual display of what happened.With Transact-SQL, you can temporarily display the result of this operation or you can store it ina table. We already saw how to do this when creating records. You follow the same formulawhen updating records. The formula is:UPDATE TableNameSET ColumnName = ExpressionOUTPUT INSERTED.ColumnsVALUES(Value_1, Value_2, Value_X)Besides the formula we have used so far, after the SET expression, start withan OUTPUTINSERTED expression, followed by a period. If you are to show all columns of thetable, add the * operator. Otherwise, type INSERTED followed by a period, followed by the nameof the column you want to show.Practical Learning: Outputting the Update1. Press Ctrl + A to select the code in the window2. To update some records and show which ones were changed, type the following:USE CeilInn2;GOUPDATE RoomsSET Rate = 95.50OUTPUT INSERTED.*WHERE BedType = NQueen;GO3. Press F5 to executeRecord Maintenance: Deleting RecordsRemoving all RecordsIf you think all records of a particular table are, or have become, useless, you can clear thewhole table, which would still keep its structure. To delete all records from a table, first select all
  10. 10. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : them, and press Delete. You would receive a warning:If you still want to delete the records, click Yes. If you change your mind, click No.The DDL command to clear a table of all records is DELETE. It uses the following formula:DELETE TableName;When this statement is executed, all records from the TableName factor would be removed fromthe table. Be careful when doing this because once the records have been deleted, you cannotget them back.Removing a RecordIf you find out that a record is not necessary, not anymore, or is misplaced, you can remove itfrom a table. To remove a record from a table, you can right-click its gray box and click Delete.You can also first select the record and press Delete. You would receive a warning to confirmyour intention.To programmatically delete a record:In the Object Explorer, you can right the table, position the mouse on Script Table As ->DELETE To -> New Query Editor WindowOpen an empty query window and type your codeIn SQL, to delete a record, use the DELETE FROM statement associate the WHEREoperator.The formula to follow is:DELETE FROM TableNameWHERE Condition(s)The TableName factor is used to identify a table whose record(s) would be removed.The Condition(s) factor allows you to identify a record or a group of records that carries acriterion. Once again, make sure you are precise in your criteria so you would not delete thewrong record(s).Here is an example used to remove a particular record from the table:DELETE FROM Videos
  11. 11. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : VideoTitle = NThe Lady Killers;Here is an example used to clear the table of all videos:DELETE FROM Videos;Outputting the Deleted ResultWhen some record(s) has(have) been deleted, the operation is performed behind the scenes andyou dont see the result. If you want to see a list of the records that were deleted, you can usethe OUTPUT operator to display the result. To show the list of the records from a table that wascompletely emptied, you can use the following formula:DELETE FROM TableNameOUTPUT DELETED.ColumnsThe OUTPUT INSERTED expression follows the description we have seen for the record update.Here is an example:USE VideoCollection6;GODELETE FROM VideosOUTPUT deleted.*GOTo show the list of the records that were deleted based on a condition, use the followingformula:DELETE FROM TableNameOUTPUT DELETED.ColumnsWHERE Condition(s)Here is an example:USE VideoCollection6;GODELETE FROM VideosOUTPUT deleted.*WHERE YearReleased IS NULL;GOPractical Learning: Ending the Lesson1. Close the query window without saving the file2. In the Object Explorer, under the Databases node, right-click WorldStatistics and clickDelete3. In the dialog box, click OK4. In the Object Explorer, under the Databases node, right-click CeilInn2 and click Delete5. In the dialog box, click OKData Entry and PermissionsIntroductionAs far as users are concerned, the primary reason for using a database is to open a table anduse its records. You on the other hand need to control who has access to a table and what aparticular user can do on it. Fortunately, Microsoft SQL Server can let you control all types ofaccess to the records of any table of your database. As seen for databases, you can grant or
  12. 12. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : access to a table, to some users individually or to a group of users. Of course, you canwork visually or programmatically.Before exercising security on a table for a user, you must have created a user account for thatuser.Managing Permissions on a TableTo visually grant or deny operations at the table level, in the Object Explorer, right-click thetable and click Properties. In the Select a Page list, click Permissions. In the Users or Roles list,click the name of the user or click Select to locate the user. In the Permissions column, locatethe type of permission you want. Manage the operations in the Grant and in the Deny columns.In Microsoft SQL Server, every operation of a table has its own permissions:More than on a database, the permissions of a table are very interconnected. This means thatgiving one type of access may not be enough to achieve the right result. This also means thatyou must know how to combine permissions:ALTER: If this permission is granted, a user can open a table in design view and change itsstructure (design). For example, a person can add a new column or delete an existingcolumn. In most cases, regular users should be denied this rightINSERT: This permission allows a user to create new records. If you dont want a user to
  13. 13. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : new records to the table, then deny this permissionUPDATE: This is one of the most important permissions when it comes to data entryDELETE: This permission allows a user to delete one or more records. The reverse is todeny this right so the user can only see the records but cannot remove themThe basic formula to programmatically grant one or more permissions to a user is:GRANT Permission1,Permission2, Permission_nON [ OBJECT :: ][ schema_name ].object_name [ (Column1, Column2, Column_n ] ) ]TO Login1, Login2, Login_n ]The basic formula to programmatically deny (a) permission(s) is:DENY Permission1,Permission2, Permission_nON [ OBJECT :: ][ schema_name ].object_name [ (Column1, Column2, Column_n ] ) ]TO Login1, Login2, Login_n ]You start with the GRANT (or DENY) keyword. To grant a permission, type it. After specifyingthe types of permissions you want, type ON or ON OBJECT::. This is followed by the name ofthe object, that is, the table, on which you want to grant permissions. If necessary, or this isoptional, precede the name of the object with the name of the schema. After the name of theobject, type TO, followed by the login name that will receive the permission. Here is anexample:USE master;GOCREATE DATABASE Exercise1;GOUSE Exercise1;GOCREATE TABLE Employees(EmployeeNumber nchar(10),FirstName nvarchar(20),LastName nvarchar(20),);GOCREATE USER [Peter Mukoko]FOR LOGIN rkouma;GOGRANT ALTERON OBJECT::EmployeesTO [Peter Mukoko];GOIf you want to combine permissions, separate them with commas. Here is an example:USE Exercise1GRANT INSERT, UPDATEON OBJECT::dbo.PayrollTO [James Galvin];GOIf you wan to grant the permission(s) to more than one account, separate them with commas.Extending PermissionsAs mentioned for a database, you can give one account the ability to grant or deny permissionsto other accounts. To do this visually, access the Database Properties for the database. In the
  14. 14. Lecturer: Tran Dinh Vuong Home page: : 0982.113.274 Email : or Roles section, select the user. In the Persmissions, use the check boxes in the WithGrant column.The formula to programmatically give an account the ability to grant or deny permissions toother accounts is:GRANT Permission1,Permission2, Permission_nTO Login1, Login2, Login_nWITH GRANT OPTIONIn this formula, you add the WITH GRANT OPTION expression.