Lession 5 the columns of a table

1,352 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
1,352
On SlideShare
0
From Embeds
0
Number of Embeds
706
Actions
Shares
0
Downloads
8
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Lession 5 the columns of a table

  1. 1. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn83Lession 5: The Columns of a TableColumns FundamentalsIntroductionIn our introduction to tables, we saw that a list could be organized in categories calledcolumns. Here is the example we saw:Name Age Gender RelationshipJudie 18 Female SisterErnest 24 Male CousinBill 52 Unknown UncleDavid 36 Male BrotherHermine 12 Unknown NieceAs you can see from this arrangement, a column is used to particularly classify one typeof data. For example, one column can be used to list some names. Another column can beused to list numbers. Yet another column can be used for a select list of items that keeprepeating those items.To organize the information that a column holds, a table needs a series of details abouteach column. Two aspects are particularly important: a name and the type of data that acolumn should/must/can hold.Practical Learning: Starting a Database1. Start Microsoft SQL Server, connect and, in the Object Explorer, expand theDatabases node2. In the Object Explorer, right-click Databases and click New Database...3. In the New Database dialog box, set the Database Name to bcr1 (it stands forBethesda Car Rental)4. Click OK5. In the Object Explorer, expand the bcr1 node (click its + button)
  2. 2. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn846. Under bcr1, right-click Tables and click New Table...The Name of a ColumnTo be able to recognize the categories of information that a column holds, the columnshould have a name. In Microsoft SQL Server, the name of a column displays in the top,the header part, of the column. The name of a column allows the database as a file toidentify the column. The name of a column also will help you, the database developer, toidentify that column. There are rules and suggestions you must or should follow whennaming the columns of a table.The name of a column:Can start with a letter, a digit, or an underscoreCan include letters, digits, and spaces in any combinationAfter respecting these rules, you can add your own rules. In our lessons, here are therules we will use to name our columns:A name will start with a letter. Examples are n, act, or SecondAfter the first character as an underscore or a letter, the name will havecombinations of underscores, letters, and digits. Examples are n24 or col_52_tUnless specified otherwise, a name will not include special characters such as !, @,#, $, %, ^, &, or *If the name is a combination of words, each word will start in uppercase. Examplesare Date Hired, LastName, Drivers License Number, or EmailAddressPractical Learning: Setting Columns NamesAs the caret is blinking under the Column Name column, type FirstNameThe Types of Data
  3. 3. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn85After deciding on the name of a column, the database needs to know what kind ofinformation the column would hold. Since there are various kinds of information adatabase can deal with, we saw in Lesson 5 the types of data that Microsoft SQL Serversupported. Therefore, you must specify the data type that is necessary for a particularcolumn.Practical Learning: Setting Data Types1. Click the arrow of the combo box under the Data Type column2. Scroll down and select nvarchar(50) from the list3. Click the first empty field under FirstName and type MI4. Press the down arrow key to position the cursor under MI5. Type LastName and press the down arrow key6. Type DateHired7. Press Tab and select date.8. Press Enter three times to position the mouse cursor under DateHired9. Type EmployeeNumber and press the down arrow key
  4. 4. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn8610.Complete the table as follows:The Length of DataA database deals with various types of data, appropriate or not for certain fields. Thismeans that you should take care of jobs behind the scenes as much as you can. One wayyou can do this is by controlling the amount of information that can be stored in aparticular field. As various columns can hold different types of data, so can the same datatype control its own mechanism of internal data entry. The length of data means differentthings to different fields. Columns that carry the same data type can have differentlengths.Bit Fields: We saw already that a bit column type is meant for one of two answers. Theuser is supposed to simply let the database know that the answer is yes or no, true orfalse, on or off, 1 or 0. Therefore, the only length of this field is 1.Integers: The length of an integer is the number of bytes its field can hold. Foran int type, that would be 4 bytes.Decimal and Floating-Point Numbers: The Length specifies how many bytes the fieldcan store.Strings: The Length of a character or string column specifies the maximum number ofcharacters that the field can hold.In some circumstances, you will need to change or specify the length as it applies to aparticular field. For example, since you should use the varchar data type for a string fieldwhose content will change from one record to another, not all varchar columns need tohave the same length. Although a First Name and a Book Title columns should usethe varchar type, both columns would not have the same length of entries. As ithappens, people hardly have a first name that is beyond 20 characters and many booktitles go beyond 32 characters. In this case, both fields would use the same data type butdifferent lengths. On the other hand, for columns ofdatetime2 and money data types,you should accept the default length suggested by the database.There are two ways you can change the length of a string-based column:
  5. 5. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn87In the top section of the windo, to change the length of the field, in the parenthesesof the data type, enter the desired valueIn the top section of the window, click the name of the column. In the bottomsection, click the Length field and type the desired valuePractical Learning: Setting Data Types1. In the top section, click MI to select it2. In the bottom section, click Length and type 13. In the top section of the table, click State and press Tab4. For the data type, type nchar(2)5. In the same way, complete the table as follows:6. To save your table, on the Standard toolbar, click the Save button7. In the Choose Name dialog box, type Employees8. Click OK9. Close the tableProgrammatic Creation of ColumnsWe saw that the primary formula to create a table was:CREATE TABLE TableName
  6. 6. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn88After specifying the name of the table, you must list the columns of the table. The list ofcolumns starts with an opening parenthesis "(". The list ends with a closing parenthesis")". Each column must be separated from the next with a comma, except for the lastcolumn. You can include all columns on the same line if possible as follows:CREATE TABLE Country(Column1, Column2, Column3)Alternatively, to make your statement easier to read, you should create each column onits own line as follows:CREATE TABLE Country(Column1,Column2,Column3);There are two primary pieces of information you must specify for each column: its nameand its type. Therefore, the syntax of creating a column is:ColumnName DataType OptionsThe name of a column should follow the same rules and suggestions we reviewed forthe columns.After typing the name of the column, type the desired or appropriate data type for thecolumn. For this example, use one of the (appropriate) data types we reviewed.Remember that some of the data types need to have a length. In the case of text-basedcolumns, when using SQL to create your columns, because it is less visual than the tabledesign of the SQL Server Management Studio, you cannot rely on the default length ofstrings suggested by SQL. As it happens, the SQL Server Management Studio specifiesdifferent default values for text-based columns. Therefore, when using SQL to create yourcolumns, you should (strongly) specify your own default length for text-based columns.We also saw that you could use sample code to create a table. This allows you to havemore control over the various columns you want the table to have. To do this, open anempty query window and display the Templates Explorer. Expand the Table node. UnderTable, you can drag Create Table, Add Column, or Drop Column, and drop it in the querywindow. If you use dropped Add Column or Drop Column, you can delete the undesiredsections of the code and isolate only the part that handles table creation. Here is anexample:--==========================================================================-- Add column template---- This template creates a table, then it adds a new column to the table.--==========================================================================USE <database, sysname, AdventureWorks>GOCREATE TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table>(column1 int,column2 char(10))GOPractical Learning: Creating a Table1. In the Object Explorer, right-click BCR1 and click New Query2. In the code editor, type the following:
  7. 7. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn89USE bcr1;GOBEGIN TRYCREATE TABLE Customers (DrvLicNbr nvarchar(32),DateIssued DATE,DateExpired date,CustomerName nvarchar(50),CustomerAddress NVARCHAR(120),CustomerCity NvarChar(40),CustomerState NVarChar(50),CustomerPostalCode nvarchar(20),HomePhone nvarchar(20),OrganDonor BIT);END TRYBEGIN CATCHSELECT NReport the following error: + ERROR_MESSAGE();END CATCHGO3. To execute the statement, press F54. Close the Query window5. When asked whether you want to save the text, click NoUsing User-Defined Data-TypesIn Lesson 5, we saw that, and how, you can create user-defined data types for existingTransact-SQL data types. In Lesson 5, we stored our types in the master database. If youare working on a database, you can create and store your new types in it. As mentionedin Lesson 5, to visually create a UDT, in the Object Explorer, expand your database,expand its Programmability node, and expand its Types node. Under Types, right-clickUser-Defined Data Types and click New User-Defined Data Type...
  8. 8. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn90In the New User-Defined Data Type dialog box, fill in the necessary information and clickOKRemember that you can also programmatically create the data type(s). Here areexamples:USE Exercise;GOCREATE TYPE NaturalNumber FROM int;GOCREATE TYPE ShortString FROM nvarchar(20);GOCREATE TYPE ItemCode FROM nchar(10);GOCREATE TYPE LongString FROM nvarchar(80);GOCREATE TYPE Salary FROM decimal(8, 2);GOCREATE TYPE Boolean FROM bit;GOAfter creating the UDT(s), you can use it(them) for your column(s). To do this visually,after displaying the table in design view, click the column name, click the arrow of theData Type combo box to display a mix of Transact-SQL types and your own defined types:
  9. 9. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn91Referring to a ColumnIntroductionWe will write many expressions that include the names of columns. In such expressions,you will need to indicate the particular column you are referring to. There are variousways you can do this. To refer to, or to indicate, a table:You must type the name of the table to which the column belongs, followed by theperiod operator, followed by the name of the column. An example wouldbeEmployee.LastNameYou can type dbo, followed by the period operator, followed by the name of the tableto which the column belongs, followed by the period operator, followed by the nameof the column. An example would be dbo.Employee.LastNameYou can type the name of the database that owns the tables column, followed by theperiod operator, followed by dbo, followed by the period operator, followed by thename of the table to which the column belongs, followed by the period operator,followed by the name of the column. An example wouldbeRedOakHighSchool.dbo.Employee.LastNameUsing the Alias Name of a TableYou can create an alias name of a table to use in an expression that involves a column. Todo this, type a letter or a word that will represent the table to which the column belongs.The letter or the word is followed by a period operator, and followed by the name of thecolumn. An example would be empl.LastName. At the end of the statement, you musttype the name of the table, followed by space, and followed by the letter or the word. Anexample would be Employee empl.Columns MaintenanceIntroductionColumn maintenance consists of reviewing or changing any of its aspects. This includesreviewing the structure of columns of a table, renaming a column, deleting a column,changing the data type or the nullity of a column, etc.Column ReviewTo see the structure of a table in the SQL Server Management Studio, in the ObjectExplorer, you can expand it:
  10. 10. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn92To view the columns of a table using SQL code, in a query window,executesp_columns followed by the name of the table the columns belong to. Here is anexample:This action displays the list of columns in the COLUMN_NAME column and othercharacteristics on the right columns.The Properties of a ColumnA column on a table controls what kind of data is appropriate for that particular column.The characteristics that identify or describe such a table are defined as its properties. Aswe have seen previously, three primary properties are particularly important and requiredfor each column: the name, the data type, and the length. Besides these, some otherproperties can be used to further control the behavior of a particular field.Besides the name, data type and length of a column, you can control the columns of atable using the Columns property sheet in the lower section of the table in Design View.These properties sometimes depend on the data type of the column. Therefore, to specifythe properties of a column, you must first select it in the upper section of the table. Thisselection can be done by just clicking either the name, the data type, or the length of thecolumn. Then you can either press F6 or click the first field in the lower section, select thedesired property and type the necessary value:
  11. 11. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn93DescriptionDescription: Common and enabled for all fields, the description is used for a sentencethat describes the column. You can type anything on that field.CollationBecause different languages use different mechanisms in their alphabetic characters, thiscan affect the way some sort algorithms or queries are performed on data, you can askthe database to apply a certain language mechanism to the field by changingtheCollation property. Otherwise, you should accept the default specified by the table.To specify the collation of a column when creating in, type COLLATE, followed by thedesired collation code. Here is an example:CREATE TABLE Customers(FullName varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS);Modifying a ColumnWhen making a change on a column, you are also said to alter the table. To support thisoperation, SQL starts with the following formula:ALTER TABLE TableName
  12. 12. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn94When using this statement, the ALTER TABLE expression is required and it is followed bythe name of the table.Adding a New ColumnAfter a table has already been created, you can still add a new column to it.To add a new column in SQL Server Management Studio, first right-click the table andclick Design Table. To add a new column to the end of the table, click the first empty fieldunder Column Name, type a name, and specify the other options.To insert a new column between two existing one, right-click the column that will succeedit and click Insert Column:This would create a new empty field. Type the desired name and specify the otheroptions.In SQL, the basic formula to add a new column to an existing table is:ALTER TABLE TableNameADD ColumnName PropertiesThe ColumnName factor is required. In fact, on the right side of the ADD keyword, definethe column by its name and using all the options we reviewed for columns.Here is an example:ALTER TABLE StaffMembersADD Address nvarchar(100) NULLGOWhen this code is executed, a new column name Address, of type nvarchar, with a limitof 100 characters, and that allow empty entry, will be added to a table namedStaffMembers in the current database.You can also use sample code to add a new column to a table. First display an emptyquery window and display the Templates Explorer. Expand the Table node. Under Table,drag Add Column and drop it in the query window. Delete the undesired sections of codeand keep only the part that deals with adding a column. Here is an example:--==========================================================================-- Add column template--
  13. 13. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn95-- This template creates a table, then it adds a new column to the table.--==========================================================================USE <database, sysname, AdventureWorks>GO-- Add a new column to the tableALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table>ADD <new_column_name, sysname, column3><new_column_datatype,, datetime><new_column_nullability,, NULL>GORenaming a ColumnIf you find out that the name of a column is not appropriate, you can change it. Torename a column in the Object Explorer, right-click the table that the column belongs toand click Modify. In the design view, highlight the name of the desired column to put itinto edit mode and edit it.In SQL, to change the name of a column, first open an empty query window. In a querywindow, execute sp_rename using the following formula:sp_rename TableName.ColumnName, NewColumnName, NCOLUMNThe sp_rename factor and the COLUMN string are required. The TableName factor isthe name of the table that the column belongs to. The ColumnName is the current nameof the column. The NewColumnName is the desired name you want to give to the column.Here is an example:sp_rename NStaffMembers.FullName, NEmployeeName, NCOLUMNGOWhen this code is executed, the interpreter will look for a column named FullName in theStaffMembers table of the current or selected database. If it finds that column in thetable, then it renames it EmployeeName.Deleting a ColumnIf you have an undesired column that you dont want anymore in a table, you can removeit. To visually delete a column, in the Object Explorer, expand the database, the Tables,and the Columns nodes. Right-click the undesired column and click Delete. The DeleteObject dialog box would display. If you still want to delete the column, click OK. Tochange your mind, click Cancel.To delete a column using code, first open or access an empty query window, and use thefollowing formula:ALTER TABLE TableNameDROP COLUMN ColumnNameOn the right side of the ALTER TABLE expression, type the name of the table. On theright side of the DROP COLUMN expression, enter the name of the undesired column.Here is an example:ALTER TABLE StaffMembersDROP COLUMN CurrentResidence;GO
  14. 14. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn96When this code is executed, the interpreter will look for a column namedCurrentResidence in a table StaffMembers of the current or selected database. If it findsthat column, it will remove it from the table.Microsoft SQL Server can also generate sample code you can use to delete a column froma table. Before doing this, first display an empty query window and display the TemplatesExplorer. Expand the Table node. In the Table section, drag Drop Column and drop it inthe query window. Delete the undesired sections of code and keep only the part that dealswith adding a column. Here is an example:--============================================-- Drop column template---- This template creates a table, then it-- drops one of the columns of the table.--============================================USE <database, sysname, AdventureWorks>GO-- Drop a column from the tableALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table>DROP COLUMN <new_column_name, sysname, column3>GOPractical Learning: Ending the Lesson1. Close the query window without saving the file2. In the Object Explorer, under the Databases node, right-click bcr1 and click Delete3. In the dialog box, click OK (if you are denied to delete the database, close MicrosoftSQL Server, reopen it, and try deleting the database again)Lesson SummaryTopics ReviewedTablesColumnsExercise: Utility Company1. Access the UtilityCompany1 database2. Visually create a table named Employees and that has the followingcolumns:EmployeeNumber, FirstName, LastName, and Title3. Create a table namedCustomers AccountNumber, DateAccountCreated,CustomerName, Address, City, State, and EmailAddressExercise: US States1. Get your research papers on US regions and New England2. On the piece of paper, complete the list with regions3. Complete the list with all states
  15. 15. Lecturer: Tran Dinh Vuong Home page: www.fit.vimaru.edu.vn/~vuongtdPhone : 0982.113.274 Email : vuongtd@vimaru.edu.vn974. Connect to the server from the Command Prompt and access theUnitedStatesRegions1 database5. Create a table named Regions with the columns Region and Description6. Create a table named States with the columns Name, Code, Area, Population,and Capital7. Exit the Command Prompt

×