Successfully reported this slideshow.

Lession 6.introduction to records

1,329 views

Published on

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

  • Be the first to like this

Lession 6.introduction to records

  1. 1. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn98Lession 6: Introduction to RecordsRecords FundamentalsIntroductionA table is an object that holds the information of a database. Because a table is the central partof a database, the information it holds must be meticulously organized. To better manage itsinformation, data of a table is arranged in a series of fields called cells.Once a table contains information, you can review it using either SQL Server Management Studioor an external application.The tables of a database display in the Object Explorer under their database node. To open a tablefor data entry, right-click it and click Edit Top 200 Rows.Table Data Navigation in the SQL Server Management StudioData Navigation consists of displaying and viewing data. Because information of a database isstored in tables, your primary means of viewing data consists of opening a table in a view thatdisplays its information.When a table displays its records, you navigate through its fields using the mouse or thekeyboard. With the mouse, to get to any cell, you can just click it. To navigate through recordsusing the keyboard, you can press:The right arrow key to move to the right cell; if the caret is already in the most right cell, itwould be moved to the first cell of the next record, up to the last empty cell of the firstempty recordThe left arrow key to move to the previous cell; if the caret is in, or reaches, the most leftcell of the first record, nothing would happen when you press the the left arrow keyThe down arrow key to move to the cell under the current one; if the caret is already in thelast cell of the current column, nothing would happenThe up arrow key to move to the cell just above the current one; if the caret is already in thefirst cell of the current column, nothing would happenThe Page Down to move to the next group of cell that would correspond to the next page; ifthe number of records is less than a complete page, the caret would move to the last cell ofthe current columnThe Page Up to move to the next group of cell that would correspond to the next page; if thenumber of records is less than a complete page, the caret would move to the first cell of thecurrent column
  2. 2. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn99Visual Data EntryIntroductionAs you are probably aware already, columns are used to organize data by categories. Each columnhas a series of fields under the column header. One of the actual purposes of a table is to displaydata that is available for each field under a particular column. Data entry consists of providing thenecessary values of the fields of a table. Data is entered into a field and every time this is done,the database creates a row of data. This row is called a record. This means that entering data alsoself-creates rows.There are four main ways you can perform data entry for a Microsoft SQL Server table:You can use a table from the Object ExplorerYou can enter data by typing code in a query windowYou can import data from another object or another databaseYou can use an external application such as Microsoft Access, Microsoft Visual Basic, BorlandC++ Builder, Microsoft Visual C++, Borland Delphi, Microsoft Visual Basic, C#, Visual C#,J#, etc.Using the Object ExplorerProbably the easiest and fastest way to enter data into a table is by using SQL ServerManagement Studio. Of course, you must first open the desired table from an available database.In the Object Explorer, after expanding the Databases and the Tables nodes, open a table for dataentry. If the table does not contain data, it would appear with one empty row:If some records were entered already, their rows would show and the table would provide anempty row at the end, expecting a new record.To perform data entry on a table, you can click in a field. Each column has a title, called a caption,on top. This gray section on top is called a column header. In SQL Server, it displays the actualname of the column. You refer to the column header to know what kind of data should/must go ina field under a particular column. This is why you should design your columns meticulously. Afteridentifying a column, you can type a value. Except for text-based columns, a field can accept orreject a value if the value does not conform to the data type that was set for the column. Thismeans that in some circumstances, you may have to provide some or more explicit information tothe user.
  3. 3. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn100Practical Learning: Introducing Data Entry1. Start Microsoft SQL Server, select the appropriate options in the Connect To Server dialogbox and connect to the server2. Right-click the server name and click New Query3. To create a new database, in the empty window, type the following:4. CREATE DATABASE WorldStatistics;5. GO6. USE WorldStatistics;7. GO8. CREATE TABLE Countries9. (10. [Country Name] NVARCHAR(50),11. Area INT,12. Population BIGINT,13. Capital NVARCHAR(50),14. [Internet Code] nchar(2)15. );GO16.To execute the SQL statement, press F517.Close the query window18.When asked whether you want to save it, click No19.In the Object Explorer, right-click Databases and click Start PowerShell20.Type SQLCMD and press Enter21.To create a new database, type the following and press Enter at the end of each line:22. USE master;23. GO24.25. IF EXISTS(SELECT name26. FROM sys.databases27. WHERE name = NCeilInn128. )29. DROP DATABASE CeilInn130. GO31.32. CREATE DATABASE CeilInn1GO33.Press Enter34.Return to Microsoft SQL Server Management Studio35.In the Object Explorer, right-click the Databases node and click Refresh. Expand theDatabases node.Under Databases, expand WorldStatistics and expand Tables36.If you dont see a table named Countries, right-click the Tables node and click Refresh.Right-click Countries and click Edit Top 200 Rows37.Click the first empty cell under CountryName, type Cote dIvoire and press Enter38.Type 322460 for the area and press Tab39.Type 16,393,221 and press Enter40.Notice that you receive an error because the commas are not allowed:
  4. 4. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn10141.Click OK on the error message box.42.Change the value to 16393221 People and press Tab43.Notice that you receive another error because the column is configured for a natural numberand not a string44.Click OK on the error message box and delete People45.Under Internet Code, type ci and press Enter46.Click the field under Capital, type Yamoussoukro and press Enter twice47.Complete the table as follows:Country Name Area Population Capital Internet CodeCote dIvoire 322460 16393221 Yamoussoukro ciPanama 78200 3191319 Panama paAustralia 7686850 20264082 Canberra auCanada 9984670 33098932 Ottawa caIran 1648000 68688433 Tehran ir48.Close the tableProgrammatic Data EntryIntroductionTo programmatically perform data entry, you use a Data Definition Language (DDL) commandknown as INSERT. To start, if you are working in Microsoft SQL Server:In the Object Explorer, you can right the table, position the mouse on Script Table As ->INSERT To -> New Query Editor Window. You may get code as follows:INSERT INTO [Exercise].[dbo].[Employees]([EmployeeNumber],[LastName],[FirstName],[Username],[DateHired],[HourlySalary])VALUES(<EmployeeNumber, int,>,<LastName, nvarchar(20),>,<FirstName, nvarchar(20),>,<Username, nchar(8),>,<DateHired, date,>
  5. 5. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn102,<HourlySalary, money,>)GOOpen an empty query window and type your codeThe DDL command to perform data entry is INSERT combined with VALUES. The primarystatement uses the following syntax:INSERT TableName VALUES(Column1, Column2, Column_n);Alternatively, or to be more precise, you can use the INTO keyword betweenthe INSERTkeyword and the TableName factor to specify that you are entering data into thetable. This is done with the following syntax:INSERT INTO TableName VALUES(Column1, Column2, Column_n)The TableName factor must be a valid name of an existing table in the database you are using. Ifthe name is wrong, the SQL interpreter would simply consider that the table you are referring todoesnt exist. Consequently, you would receive an error.The VALUES keyword indicates that you are ready to list the values of the columns. The values ofthe columns must be included in parentheses.If the column is a BIT data type, you must specify one of its values as 0 or 1.If the column is a numeric type, you should pay attention to the number you type. If the columnwas configured to receive an integer (int, bigint, smallint), you should provide a valid naturalnumber without the decimal separator.If the column is for a decimal number (float, real, decimal, numeric), you can type the valuewith its character separator (the period for US English).If the column was created for a date data type, make sure you provide a valid date.If the data type of a column is a string type, you should include its entry between single quotes.For example, a shelf number can be specified as HHR-604 and a middle initial can be given asD.In the previous paragraphs, we were stating "you" as if you will be the one performing data entry. Inreality, the user will be performing data entry on your products. Therefore, it is your responsibility toreduce, as much as possible, the likelihood of mistakes. Of course, there are various ways, through a"visual" application such as Borland C++ Builder, Microsoft Visual Basic, C#, or MS Visual C++, etc, thatyou can take care of this.Adjacent Data EntryThe most common technique of performing data entry requires that you know the sequence offields of the table in which you want to enter data. With this subsequent list in mind, enter thevalue of each field in its correct position.During data entry on adjacent fields, if you dont have a value for a numeric field, you should type0 as its value. For a string field whose data you dont have and cannot provide, type two single-quotes to specify an empty field.Practical Learning: Performing Adjacent Data Entry1. To open a new query window, press Ctrl + N2. In the query window, to create one record, type:
  6. 6. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn103USE WorldStatistics;GOINSERT INTO CountriesVALUES(NAngola, 1246700, 12127071, NLuanda, Nao);GO3. Press F5 to execute4. Delete the top section of the window5. To enter various records at the same time, enter the following statement:USE WorldStatistics;GOINSERT INTO CountriesVALUES(NMexico, 1972550, 107449525, NMexico City, Nmx);(NSouth Africa, 1219912, 44187637, NPretoria, Nza);(NIraq, 0, 0, NBaghdad, Niq);(NUnited States, 9826630, 0, N, N);(NSaudi Arabia, 2149690, 0, NRiyadh, N);GO6. Press F5 to execute the statementRandom Data EntryThe adjacent data entry we have performed requires that you know the position of each column.The SQL provides an alternative that allows you to perform data entry using the name of a columninstead of its position. This allows you to provide the values of columns in an order of your choice.We have just seen a few examples where the values of some of the fields were not availableduring data entry. Instead of remembering to type 0 or NULL for such fields or leaving emptyquotes for a field, you can use the fields names to specify the fields whose data you want toprovide.To perform data entry in an order of your choice, you must provide your list of the fields of thetable. You can either use all columns or provide a list of the same columns but in your own order.In the same way, you dont have to provide data for all fields, just those you want, in the orderyou want.Practical Learning: Performing Random Data Entry1. To perform data entry, type and execute the following statement:USE WorldStatistics;GOINSERT Countries([Country Name],Capital,[InternetCode],Population,Area)VALUES(NChina, NBeijing, Ncn, 1313973713, 9596960)GO2. Press F5 to execute the statement3. To perform other entries, type the following statement:USE WorldStatistics;GOINSERT Countries(Capital, [Internet Code], [Country Name])VALUES(NNouakchott, Nmr, NMauritania)GO
  7. 7. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn104INSERT Countries([Internet Code], Population, [Country Name])VALUES(Nro, 22303552, NRomania)GOINSERT Countries(Area, [Country Name], Population)VALUES(21040, NEl Salvador, 6822378)GOINSERT Countries(Capital, [Country Name])VALUES(NPhnom Penh, NCambodia)GO4. To execute the statement, press F55. Close the query window6. When asked whether you want to save it, click NoCreating Multiple RecordsIn previous sections, we added a single record to each use of the INSERT formula. You can addvarious records with one call to INSERT. If you are adding a value to each column of the table,after the name of the table, type VALUES, open and close the first parentheses. Inside theparentheses, include the desired values. To add another record, type a comma after the closingparenthesis, open a new parenthesis, list the new values, and close the parenthesis. Do this asmany times as you need to add records. Here is an example:-- =============================================-- Database: Video Collection-- =============================================USE masterGO-- Drop the database if it already existsIF EXISTS (SELECT nameFROM sys.databasesWHERE name = NVideoCollection)DROP DATABASE VideoCollectionGOCREATE DATABASE VideoCollectionGO-- =============================================-- Database: Video Collection-- Table: Videos-- =========================================USE VideoCollectionGOIF OBJECT_ID(NVideos, NU) IS NOT NULLDROP TABLE VideosGOCREATE TABLE Videos(Title nvarchar(50),Director nvarchar(50),Rating nchar(10),YearReleased int)GO
  8. 8. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn105INSERT INTO VideosVALUES(NHer Alibi, NBruce Beresford, NPG-13, 1998),(NMemoirs of a Geisha, NRob Marshall, NPG-13, 2006),(NTwo for the Money, ND.J. Caruso, NR, 2008);GOThis is valid for adjacent data entry. If you want to follow your own order of columns, on the rightside of the name of the table, include a list of columns in parentheses. Then, when giving thevalues, for each record, follow the order in which you listed the columns. Here is an example:-- =============================================-- Database: Video Collection-- =============================================USE masterGO-- Drop the database if it already existsIF EXISTS(SELECT nameFROM sys.databasesWHERE name = NVideoCollection)DROP DATABASE VideoCollectionGOCREATE DATABASE VideoCollectionGO-- =============================================-- Database: Video Collection-- Table: Videos-- =========================================USE VideoCollectionGOIF OBJECT_ID(NVideos, NU) IS NOT NULLDROP TABLE VideosGOCREATE TABLE Videos(Title nvarchar(50),Director nvarchar(50),Rating nchar(10),YearReleased int)GOINSERT INTO Videos(Rating, Title, Director)VALUES(NR, NWall Street, NOliver Stone),(N, NMichael Jackson Live in Bucharest, NAndy Morahan),(NPG-13, NSneakers, NPaul Alden Robinson),(NR, NSoldier, NPaul Anderson);GOOutputting the Insertion ResultIn the techniques we have used so far, when or if the records have been added to a table,whether the operation was successful or not, we had no way of immediately finding out (we wouldhave to open the table). One way you can get this information is to store the inserted records inanother table. To support this, Transact-SQL provides the OUTPUT operator. The formula to useit is:
  9. 9. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn106INSERT INTO TableNameOUTPUT INSERTED.ColumnsVALUES(Value_1, Value_2, Value_X)You start with the normal record insertion with the INSERT INTO TableName expression. This isfollowed by the OUTPUT operator followed by the INSERTED operator and a period. If you areadding a value for each record, follow the period with *. The statement continues withthe VALUES operator that is followed by parentheses in which you list the values to be added tothe table. Here is an example:USE VideoCollection;GOCREATE TABLE Videos(Title nvarchar(50),Director nvarchar(50),WideScreen bit,Rating nchar(10),YearReleased int)GOINSERT INTO VideosOUTPUT inserted.*VALUES(NWar of the Roses (The), NDany de Vito, 0, NR, 2001),(NMemoirs of a Geisha, NRob Marshall, 1, NPG-13, 2006),(NLast Castle (The), NRod Lurie, 1, N, 2001),(NSneakers, NPhil Alden Robinson, 1, NPG-13, 2003);GOWhen this statement executes, if you are working in the Microsoft SQL Server ManagementStudio, the lower part would display a list of the records that were added:
  10. 10. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn107If you use the above formula, when you close the database, the reference is lost. If you want tostore the list of newly created records in a table, on the right side of the INSERTEDoperator andits period, type INTO followed by the name of the table that will receive the values. The tablemust have been created; that is, it must exist at the time this inserted operation is taking place.Here is an example:USE VideoCollection;GOCREATE TABLE Archives(Title nvarchar(50),Director nvarchar(50),WideScreen bit,Rating nchar(10),YearReleased int)GOINSERT INTO VideosOUTPUT inserted.* INTO ArchivesVALUES(NTwo for the Money, ND.J. Caruso, 1, NR, 2006),(NWall Street, NOliver Stone, 0, NR, 2000);GOIn this case, a copy of the newly created records would be stored in the indicated table.The above techniques assume that you are adding a complete record; that is, you are providing avalue for each column of the table. We already saw that if you want to provide values for onlysome columns, after the name of the table, provide the list of columns in parentheses. To get thelist of newly inserted records, after the OUTPUT keyword, typeINSERTED followed by a periodand followed by the name of the first column. Do this for each column and separate them withcommas. The formula to use is:INSERT INTO TableName(Column_1, Column_2, Column_X)OUTPUT INSERTED.Column_1, INSERTED.Column_2, INSERTED.Column_XVALUES(Value_1, Value_2, Value_X)Of course, you can list the columns in an order of your choice, as long as both the TableNameandthe OUTPUT section use the exact same order. Here is an example:USE VideoCollection;GOINSERT INTO Videos(Director, Rating, Title)OUTPUT inserted.Director, inserted.Rating, inserted.TitleVALUES(NJonathan Lynn, NR, NDistinguished Gentleman (The)),(NPaul Anderson, NR, NSoldier);GOIn this case, when the statement has executed, the result would display in the lower portion ofthe Microsoft SQL Server Management Studio. If you want to store the result in a table, use thefollowing formulaINSERT INTO TableName(Column_1, Column_2, Column_X)OUTPUT INSERTED.Column_1, INSERTED.Column_2, INSERTED.Column_X INTO TargetTableVALUES(Value_1, Value_2, Value_X)Here is an example:USE VideoCollection;
  11. 11. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn108GOCREATE TABLE Entertainment(Title nvarchar(50),Director nvarchar(50))GOINSERT INTO Videos(Title, Director)OUTPUT inserted.Title, inserted.Director INTO EntertainmentVALUES(NMichael Jackson Live in Bucharest, NAndy Morahan),(NOutfoxed, NRobert Greenwald);GOTables Columns and ExpressionsIntroductionThere are various ways you can assist the user with data entry. For example, you can create anexpression using operators. You can create an expression when creating a table, whether in theTable window or using SQL in a query window.Visually Creating an ExpressionTo visually create an expression when creating a table, in the top section, specify the columnsname (only the column name is important). In the bottom section, expand the Computed ColumnSpecification field and, in its (Formula) field, enter the desired expression. Here is an example:
  12. 12. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn109Creating a SQL ExpressionYou can also create an expression in SQL expression you are using to create a table. To do this, inthe placeholder of the column, enter the name of the column, followed by AS, and followed by thedesired expression. Here is an example:CREATE TABLE Circle(CircleID int identity(1,1) NOT NULL,Radius decimal(8, 3) NOT NULL,Area AS Radius * Radius * PI());GOUsing an Expression During Data EntryWhen performing data entry, you must not provide a value for a column that has an expression;the SQL interpreter would provide the value automatically. Here is an example of entering data forthe above Circle table:INSERT INTO Circle(Radius) VALUES(46.82);GOINSERT INTO Circle(Radius) VALUES(8.15);GOINSERT INTO Circle(Radius) VALUES(122.57);GOThe Nullity of a FieldIntroductionDuring data entry, users of your database will face fields that expect data. Sometimes, for onereason or another, data will not be available for a particular field. An example would be an MI(middle initial) field: some people have a middle initial, some others either dont have it orwould not (or cannot) provide it. This aspect can occur for any field of your table. Therefore,you should think of a way to deal with it.A field is referred to as null when no data entry has been made to it:Saying that a field is null doesnt mean that it contains 0 because 0 is a valueSaying that a field is null doesnt mean that it is empty. A field being empty could meanthat the user had deleted its content or that the field itself would not accept what the userwas trying to enter into that field, but an empty field can have a valueA field is referred to as null if there is no way of determining the value of its content (in reality,the computer, that is, the operating system, has its own internal mechanism of verifying thevalue of a field) or its value is simply unknown. As you can imagine, it is not a good idea tohave a null field in your table. As a database developer, it is your responsibility to always knowwith certainty the value held by each field of your table.A field is referred to as required if the user must provide a value for it before moving toanother record. In other words, the field cannot be left empty during data entry.To solve the problem of null and required fields, Microsoft SQL Server proposes one of twooptions: allow or not allow null values on a field. For a typical table, there are pieces ofinformation that the user should make sure to enter; otherwise, the data entry would not bevalidated. To make sure the user always fills out a certain field before moving to the next field,
  13. 13. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn110that is, to require the value, if you are visually creating the table, clear the Allow Nulls checkbox for the field. On the other hand, if the value of a field is not particularly important, forexample if you dont intend to involve that value in an algebraic operation, check its Allow Nullscheck box.NULL or NOT NULL?If creating a table using SQL, to specify that it can allow null values, type NULL on the rightside of the column. To specify that the values of the column are required, on the right side,type NOT NULL. If you dont specify NULL or NOT NULL, the column will be createdas NULL. Here are examples:CREATE TABLE Persons(FirstName nvarchar(20) NULL,LastName nvarchar(20) NOT NULL,Gender smallint);GOIf the table was already created and it holds some values already, you cannot set the AllowNulls option on columns that dont have values.After specify that a column would NOT allow NULL values, if the user tries creating a recordbut omits to create a value for the column, an error would display. Here is an example:This error message box indicates that you attempted to submit a null value for a column. Tocancel the action, you can press Esc.Practical Learning: Applying Fields Nullity1. In the Object Explorer, right-click Countries in the WorldStatistics node and click Modify2. Apply the nullity of fields as follows:
  14. 14. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn1113. Save the tableThe Default Value of a ColumnIntroductionSometimes most records under a certain column may hold the same value although just a fewwould be different. For example, if a school is using a database to register its students, all ofthem are more likely to be from the same state. In such a case, you can assist the user byautomatically providing a value for that column. The user would then simply accept the valueand change it only in the rare cases where the value happen to be different. To assist the userwith this common value, you create what is referred to as a default value.Visually Creating a Default ValueYou can create a default value of a column when creating a table. To specify the default valueof a column, in the top section, click the column. In the bottom section, click Default Value orBinding, type the desired value following the rules of the columns data type:It the Data Type is IntructionsText-based(char,varchar, text, andtheir variants)Enter the value in single-quotesNumeric-basedEnter the value as a number but following the rules ofthe data type.For example, if you enter a value higher than 255 fora tinyint, you would receive an errorDate or TimeEnter the date as either MM/DD/YYYY or YYYY/MM/DD.You can optionally include the date in single-quotes.Enter the time following the rules set in the ControlPanel (Regional Settings).Bit Enter True or FalseProgrammatically Creating a Default ValueTo specify the default value in a SQL statement, when creating the column, after specifying theother pieces of information of the column, type DEFAULT followed by an empty space andfollowed by the desired value. Here are examples:CREATE TABLE Employees(FullName NVARCHAR(50),Address NVARCHAR(80),City NVARCHAR(40),State NVARCHAR(40) DEFAULT LNSW,PostalCode NVARCHAR(4) DEFAULT L2000,
  15. 15. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn112Country NVARCHAR(20) DEFAULT LAustralia);GOWhen performing data entry on the table, the user does not have to provide a value for acolumn that has a default. If the user does not provide the value, the default would be usedwhen the record is saved.If the user provides a value for a column that has a default value and then deletes the value, the defaultvalue rule would not apply anymore: The field would simply become empty.Practical Learning: Assigning a Default Value to a Column1. Display the PowerShell window2. To change the database, type the following and press Enter at the end:USE CeilInn1;GO3. To create a new table whose columns have default values, type the following and pressEnter at the end:CREATE TABLE Rooms (RoomNumber nvarchar(10),RoomType nvarchar(20) default NBedroom,BedType nvarchar(40) default NQueen,Rate money default 75.85,Available bit default 0);GO4. To perform data entry on the new table, type the following and press Enter at the end:INSERT INTO Rooms(RoomNumber) VALUES(104);GO5. To add another record to the new table, type the following:INSERT INTO Rooms(RoomNumber, BedType, Rate, Available)VALUES(105, NKing, 85.75, 1),(106, NKing, 85.75, 1)GO6. To add another record, type the following:INSERT INTO Rooms(RoomNumber, Available) VALUES(107, 1)GO7. To add another record, type the following:INSERT INTO Rooms(RoomNumber, BedType, Rate) VALUES(108, NKing,85.75)GO8. To add another record, type the following:
  16. 16. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn113INSERT INTO Rooms(RoomNumber, Available) VALUES(109, 1)GO9. To add one more record, type the following:INSERT INTO Rooms(RoomNumber, RoomType, BedType, Rate, Available)VALUES(110, NConference, N, 450.00, 1)GO10.Return to Microsoft SQL Server Management StudioIdentity ColumnsIntroductionOne of the goals of a good table is to be able to uniquely identity each record. In most cases,the database engine should not confuse two records. Consider the following table:Category Item Name Size Unit PriceWomen Long-sleeve jersey dress Large 39.95Boys Iron-Free Pleated Khaki Pants S 39.95Men Striped long-sleeve shirt Large 59.60Women Long-sleeve jersey dress Large 45.95Girls Shoulder handbag 45.00Women Continental skirt Petite 39.95Imagine that you want to change the value of an item named Long-sleeve jersey dress.Because you must find the item programmatically, you can start looking for an item with thatname. This table happens to have two items with that name. You may then decide to look foran item using its category. In the Category column, there are too many items named Women.In the same way, there are too many records that have a Large value in the Size column,same thing problem in the Unit Price column. This means that you dont have a good criterionyou can use to isolate the record whose Item Name is Long-sleeve shirt.To solve the problem of uniquely identifying a record, you can create a particular columnwhose main purpose is to distinguish one record from another. To assist you with this, the SQLallows you to create a column whose data type is an integer type but the user doesnt have toenter data for that column. A value would automatically be entered into the field when a newrecord is created. This type of column is called an identity column.You cannot create an identity column one an existing table, only on a new table.Visually Creating an Identity ColumnTo create an identity column, if you are visually working in the design view of the table, in thetop section, specify the name of the column. By tradition, the name of this column resemblesthat of the table but in singular. Also, by habit, the name of the column ends with _id, Id, orID.After specifying the name of the column, set its data type to an integer-based type. Usually,the data type used is int. In the bottom section, click and expand the IdentitySpecification property. The first action you should take is to set its (Is Identity) propertyfrom No to Yes.Once you have set the value of the (Is Identity) property to Yes, the first time the userperforms data entry, the value of the first record would be set to 1. This characteristic is
  17. 17. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn114controlled by the Identity Seed property. If you want the count to start to a value other than1, specify it on this property.After the (Is Identity) property has been set to Yes, the SQL interpreter would increment thevalue of each new record by 1, which is the default. This means that the first record wouldhave a value of 1, the second would have a value of 2, and so on. This aspect is controlled bythe Identity Increment property. If you want to increment by more than that, you canchange the value of the Identity Increment property.Practical Learning: Creating an Identity Column1. In the Object Explorer, under WorldStatistics, right-click Tables and click New Table...2. Set the name of the column to ContinentID and press Tab3. Set its data type to int and press F6.In the lower section of the table, expand Identity Specification and double-click (IsIdentity) to set its value to Yes4. Complete the table as follows:Column Name Data Type Allow NullsContinentIDContinent varchar(80) UncheckedArea bigintPopulation bigint5. Save the table as ContinentsCreating an Identity Column Using SQLIf you are programmatically creating a column, to indicate that it would be used as an identitycolumn after its name and data type, type identity followed by parentheses. Between theparentheses, enter the seed value, followed by a comma, followed by the increment value.Here is an example:CREATE TABLE StoreItems(ItemID int IDENTITY(1, 1) NOT NULL,Category varchar(50),[Item Name] varchar(100) NOT NULL,Size varchar(20),[Unit Price] money);GOPractical Learning: Creating an Identity Column Using SQL1. Display the PowerShell window2. Type the following:USE CeilInn1;GO3. To create a table with an identity column, type the following and press Enter after eachline:DROP TABLE Rooms;GO
  18. 18. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn115CREATE 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);GO4. To perform data entry on the new table, type the following and press Enter at the end:INSERT INTO Rooms(RoomNumber) VALUES(104);GO5. To add another record to the new table, type the following:INSERT INTO Rooms(RoomNumber, BedType, Rate, Available)VALUES(105, NKing, 85.75, 1),(106, NKing, 85.75, 1)GO6. To add another record, type the following:INSERT INTO Rooms(RoomNumber, Available) VALUES(107, 1)GO7. To add another record, type the following:INSERT INTO Rooms(RoomNumber, BedType, Rate) VALUES(108, NKing,85.75)GO8. To add another record, type the following:INSERT INTO Rooms(RoomNumber, Available) VALUES(109, 1)GO9. To add one more record, type the following:INSERT INTO Rooms(RoomNumber, RoomType, BedType, Rate, Available)VALUES(110, NConference, N, 450.00, 1)GO10.Return to Microsoft SQL Server Management StudioThe Uniqueness of RecordsIntroductionOne of the primary concerns of records is their uniqueness. In a professional database, youusually want to make sure that each record on a table is unique. Microsoft SQL Server providesmany means of taking care of this. These include the identity column, the primary key, and theindexes. We will review these issues in later lessons. Still, one way to do this is to apply auniqueness rule on a column.
  19. 19. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn116Creating a Uniqueness RuleTo assist you with creating a columns whose values will be distinguishable, Transact-SQLprovides the UNIQUE operator. To apply it on a column, after the data type, type UNIQUE.Here is an example:USE Exercise;GOCREATE TABLE Students(StudentNumber int UNIQUE,FirstName nvarchar(50),LastName nvarchar(50) NOT NULL);GOWhen a column has been marked as unique, during data entry, the user must provide a uniquevalue for each new record created. If an existing value is assigned to the column, this wouldproduce an error:USE Exercise;GOCREATE TABLE Students(StudentNumber int UNIQUE,FirstName nvarchar(50),LastName nvarchar(50) NOT NULL);GOINSERT INTO StudentsVALUES(24880, NJohn, NScheels),(92846, NRénée, NAlmonds),(47196, NPeter, NSansen),(92846, NDaly, NCamara),(36904, NPeter, NSansen);GOBy the time the fourth record is entered, since it uses a student number that exists already,the database engine would produce an error:Msg 2627, Level 14, State 1, Line 2Violation of UNIQUE KEY constraint UQ__Students__DD81BF6C145C0A3F.Cannot insert duplicate key in object dbo.Students.The statement has been terminated.Practical Learning: Applying Uniqueness to a Column1. In the PowerShell window, to create a new table that has a uniqueness rule on a column,type the following:CREATE TABLE Customers (CustomerID int identity(1, 1) NOT NULL,AccountNumber nchar(10) UNIQUE,FullName nvarchar(50));GO2. To perform data entry on the table, type the following and press Enter at the end of each
  20. 20. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn117line:INSERT INTO Customers(AccountNumber, FullName)VALUES(395805, NAnn Zeke),(628475, NPeter Dokta),(860042, NJoan Summs)GO3. To try adding another record to the table, type the following and press Enter at the end ofeach line:USE CeilInn1;GOINSERT INTO Customers(AccountNumber, FullName)VALUES(628475, NJames Roberts)GO4. Notice that you receive an errorOther Features of Data EntryIs RowGuidThis property allows you to specify that a column with the Identity property set to Yes is usedas a ROWGUID column.CollationBecause different languages use different mechanisms in their alphabetic characters, this canaffect the way some sort algorithms or queries are performed on data, you can ask thedatabase to apply a certain language mechanism to the field by changingthe Collationproperty. Otherwise, you should accept the default specified by the table.To find out what language your server is currently using, in a Query window or fromPowerShell, you can type:SELECT @@LANGUAGE;GOData 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 ordeny 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 the
  21. 21. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn118table 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 permission: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 changeits structure (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 toadd new records to the table, then deny the INSERT 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 of
  22. 22. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn119the 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, you can give an account the ability to grant or deny permissions to anotheraccount. To do this visually, access the Database Properties for the database. In the Users orRoles section, select the user. In the Persmissions, use the check boxes in the With Grantcolumn.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.

×