database records

Upload: michael-ndavi

Post on 03-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 Database Records

    1/20

    QL Server - Lesson 09: The Records of a Database

    The Records of a Database

    troduction

    To perform data entry using SQL:

    q In the Object Explorer, you can right the table, position the mouse on Script Table As ->INSERT To -> New Query Editor Window

    q Open an empty query window and type your code

    n the SQL, data entry is performed using the INSERT combined with the VALUES keywords. The

    rimary statement uses the following syntax:

    SERT TableName VALUES(Column1, Column2, Column_n);

    Here is an example:

    SERT Countries([Country Name],Capital,[Internet Code],Population,Area)

    LUES('China', 'Beijing', 'cn', 1313973713, 9596960);

    Alternatively, you can use the INTO keyword between the INSERT keyword and the TableName factor:

    SERT 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.

    re is an example:

    SERT INTO Countries

    LUES('South Africa', 1219912, 44187637, 'Pretoria','za')

    he Default Value of a Column

    ntroduction

    Sometimes 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.

    isually Creating a Default Value

    You 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 or

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (1 of 20)11/26/2008 5:23:36 PM

    http://functionx.com/sqlserver/index.htmhttp://c.casalemedia.com/c?s=56757&f=2&id=4702601599.724939
  • 7/28/2019 Database Records

    2/20

    QL Server - Lesson 09: The Records of a Database

    Binding, type the desired value following the rules of the column's data type:

    t the Data Type is Intructions

    ext-based (char, varchar,ext, and their variants)

    Enter the value in single-quotes

    umeric-based

    Enter the value as a number but followingthe rules of the data type.For example, if you enter a value higherthan 255 for a tinyint, you would receivean error

    ate or Time

    Enter the date as either MM/DD/YYYY orYYYY/MM/DD. You can optionally includethe date in single-quotes.Enter the time following the rules set inthe Control Panel (Regional Settings).

    tEnter the value as 0 for FALSE or anyother long integer value for TRUE

    rogrammatically Creating a Default Value

    To specify the default value in a SQL statement, when creating the column, before the semi-

    colon or the closing parenthesis of the last column, assign the desired value to the DEFAULTkeyword. Here are examples:

    EATE TABLE Employees

    FullName VARCHAR(50),

    Address VARCHAR(80),

    City VARCHAR(40),

    State VARCHAR(40) DEFAULT = 'NSW',

    PostalCode VARCHAR(4) DEFAULT = '2000',

    Country VARCHAR(20) DEFAULT = 'Australia'

    After creating the table, the user does not have to provide a value for a column that has adefault. If the user does not provide the value, the default would be used when the record issaved.

    If the user provides a value for a column that has a default value and then deletes thevalue, the default value rule would not apply anymore: The field would simply becomeempty

    dentity Columns

    ntroduction

    One 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 Price

    Women Long-sleeve jersey dress Large 39.95

    Boys Iron-Free Pleated Khaki Pants S 39.95

    Men Striped long-sleeve shirt Large 59.60

    Women Long-sleeve jersey dress Large 45.95

    Girls Shoulder handbag 45.00

    Women Continental skirt Petite 39.95

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (2 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    3/20

    QL Server - Lesson 09: The Records of a Database

    Imagine 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, samething problem in the Unit Price column. This means that you don't have a good criterion youcan 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 doesn't 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.

    isually Creating an Identity Column

    To 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, or ID.

    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 Identity Specificationproperty. The first action you should take is to set its (Is Identity) property from 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 iscontrolled 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 Column in the Designable

    1. In the Object Explorer, under WorldStatistics, right-click Tables and click New Table...

    2. Set the name of the column to ContinentID and press Tab

    3. 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 Yes

    4. Complete the table as follows:

    Column Name Data Type Allow Nulls

    ContinentID

    Continent varchar(80) Unchecked

    Area bigint

    Population bigint

    5. Save the table as Continents

    reating an Identity Column Using SQL

    If 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:

    EATE TABLE StoreItems(

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (3 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    4/20

    QL Server - Lesson 09: The Records of a Database

    emID int IDENTITY(1, 1) NOT NULL,

    tegory varchar(50),

    tem Name] varchar(100) NOT NULL,

    ze varchar(20),

    nit Price] money);

    unctions and Data Entry

    ntroduction

    You can involve a function during data entry. As an example, you can call a function thatreturns a value to assign that value to a column. You can first create your own function anduse it, or you can use one of the built-in functions.

    sing Functions

    In order to involve a function with your data entry, you must have and identity one. You canuse one of the built-in functions of Transact-SQL. You can check one of the functions wereviewed in Lesson 7. Normally, the best way is to check the online documentation to find out

    f the assignment you want to perform is already created. Using a built-in function would spaceyou the trouble of getting a function. For example, imagine you have a database namedAutoRepairShop and imagine it has a table used to create repair orders for customers:

    EATE TABLE RepairOrders

    RepairID int Identity(1,1) NOT NULL,

    CustomerName varchar(50),

    CustomerPhone varchar(20),

    RepairDate DateTime

    When performing data entry for this table, you can let the user enter the customer name andphone number. On the other hand, you can assist the user by programmatically entering thecurrent date. To do this, you would call the GETDATE() function. Here are examples:

    SERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate)

    VALUES('Annette Berceau', '301-988-4615', GETDATE());

    SERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate)

    VALUES('(240) 601-3795', 'Paulino Santiago', GETDATE());

    SERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone)

    VALUES('Alicia Katts', GETDATE(), '(301) 527-3095');

    SERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName)

    VALUES(GETDATE(), '703-927-4002', 'Bertrand Nguyen');

    You can also involve the function in an operation, then use the result as the value to assign toa field. You can also call a function that takes one or more arguments; make sure you respect

    the rules of passing an argument to a function when calling it.

    If none of the Transact-SQL built-in functions satifies your requirements, you can create yourown, using the techniques we studied in Lesson 6.

    sing Expressions For Data Entry

    ntroduction

    There are various ways you can assist the user with data entry. Besides using a function, youcan create an expression using operators such as those we reviewed in lessons 3 and 5. Youcan create an expression when creating a table, whether in the Table window or using SQL in aquery window.

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (4 of 20)11/26/2008 5:23:36 PM

    http://functionx.com/sqlserver/Lesson07.htmhttp://functionx.com/sqlserver/Lesson07.htm#GETDATEhttp://functionx.com/sqlserver/Lesson06.htmhttp://functionx.com/sqlserver/Lesson06.htmhttp://functionx.com/sqlserver/Lesson07.htm#GETDATEhttp://functionx.com/sqlserver/Lesson07.htm
  • 7/28/2019 Database Records

    5/20

    QL Server - Lesson 09: The Records of a Database

    isually Creating an Expression

    To create an expression when visually creating a table, in the top section, specify the column'sname (only the column name is important). In the bottom section, expand the ComputedColumn Specification field and, in its (Formula) field, enter the desired expression. Here is anexample:

    reating a SQL Expression

    You can also create an expression in SQL expression you are using to create a table. To dothis, in the placeholder of the column, enter the name of the column, followed by AS, andfollowed by the desired expression. Here is an example:

    EATE TABLE Circle

    CircleID int identity(1,1) NOT NULL,

    Radius decimal(8, 3) NOT NULL,

    Area AS Radius *Radius * PI()

    sing an Expression During Data Entry

    When performing data entry, you must not provide a value for a column that has anexpression; the SQL interpreter would provide the value automatically. Here is an example ofentering data for the above Circle table:

    SERT INTO Circle(Radius) VALUES(46.82);

    SERT INTO Circle(Radius) VALUES(8.15);

    SERT INTO Circle(Radius) VALUES(122.57);

    heck Constraints

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (5 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    6/20

    QL Server - Lesson 09: The Records of a Database

    ntroduction

    When performing data entry, in some columns, even after indicating the types of values youexpect the user to provide for a certain column, you may want to restrict a range of values thatare allowed. To assist you with checking whether a newly entered value fits the desired range,Transact-SQL provides what is referred to as a check constraint.

    A check constraint is a Boolean operation performed by the SQL interpreter. The interpreterexamines a value that has just been provided for a column. If the value is appropriate:

    1. The constraint produces TRUE2. The value gets accepted

    3. The value is assigned to the column

    If the value is not appropriate:

    1. The constraint produces FALSE

    2. The value gets rejected

    3. The value is not assigned to the column

    You create a check constraint at the time you are creating a table.

    isually Creating a Check Constraint

    To create a check constraint, when creating a table, right-click anywhere in (even outside) thetable and click Check Constraints...

    This would open the Check Constraints dialog box. From that window, you can click Add.Because a constraint is an object, you must provide a name for it. The most important piece ofnformation that a check constraint should hold is the mechanism it would use to check itsvalues. This is provided as an expression. Therefore, to create a constraint, you can clickExpression and click its ellipsis button. This would open the Check Constraint Expression dialogbox.

    To create the expression, first type the name of the column on which the constraint will apply,followed by parentheses. In the parentheses, use the arithmetic and/or SQL operators westudied already. Here is an example that will check that a new value specified for the StudentNumber is greater than 1000:

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (6 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    7/20

    QL Server - Lesson 09: The Records of a Database

    After creating the expression, you can click OK. If the expression is invalid, you would receivean error and given the opportunity to correct it.

    You can create as many check constraints as you judge necessary for your table:

    After creating the check constraints, you can click OK.

    rogrammatically Creating a Check Constraint

    To create a check constraint in SQL, first create the column on which the constraint will apply.Before the closing parenthesis of the table definition, use the following formula:

    NSTRAINT name CHECK (expression)

    The CONSTRAINT and the CHECK keywords are required. As an object, make sure youprovide a name for it. Inside the parentheses that follow the CHECK operator, enter theexpression that will be applied. Here is an example that will make sure that the hourly salaryspecified for an employee is greater than 12.50:

    EATE TABLE Employees

    [Employee Number] nchar(7),

    [Full Name] varchar(80),

    [Hourly Salary] smallmoney,

    CONSTRAINT CK_HourlySalary CHECK ([Hourly Salary] > 12.50)

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (7 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    8/20

    QL Server - Lesson 09: The Records of a Database

    It is important to understand that a check constraint it neither an expression nor a function. Acheck constraint contains an expression and may contain a function as part of its definition.

    After creating the constraint(s) for a table, in the Object Explorer of Microsoft SQL ServerManagement Studio, inside the table's node, there is a node named Constraints and, if youexpand it, you would see the name of the constraint.

    With the constraint(s) in place, during data entry, if the user (or your code) provides an invalidvalue, an error would display. Here is an example:

    Instead of an expression that uses only the regular operators, you can use a function to assistn the checking process. You can create and use your own function or you can use one of thebuilt-in Transact-SQL functions.

    ther Features of Data Entry

    RowGuid

    This property allows you to specify that a column with the Identity property set to Yes is usedas a ROWGUID column.

    ollation

    Because 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 changing the Collationproperty. Otherwise, you should accept the default specified by the table.

    ata ImportAnother technique 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 onalmost all database environments, is the text file. Almost every database environment allowsyou to import a text file but data from that file must be formatted appropriately. For example,the information stored in the file must define the columns as distinguishable by a characterthat serves as a separator. This separator can be the single-quote, the double-quote, or anyvalid character. Data between the quotes is considered as belonging to a distinct field. Besidesthis information, 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 the comma as such a character. The last piece of information the file must provide isto distinguish each record from another. This is easily taken car of by the end of line of arecord. This is also recognized as the carriage return.

    These directives can help you manually create a text file that can be imported into MicrosoftSQL Server. In practicality, if you want to import data that resides on another database, youcan ask that application to create the source of data. Most applications can do that and formatthe data. That is the case for the data we will use in the next exercise: it is data that residedon a Microsoft Access 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 Source

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (8 of 20)11/26/2008 5:23:36 PM

    http://functionx.com/sqlserver/tables/error1.gif
  • 7/28/2019 Database Records

    9/20

    QL Server - Lesson 09: The Records of a Database

    1. Download the Students text file and save it to your hard drive

    2. In the SQL Server Management Studio, right-click the Databases node and click NewDatabase...

    3. Type ROSH and press Enter

    4. In the Object Explorer, right-click ROSH, position the mouse on Tasks and click ImportData

    5. On the first page of the wizard, click Next

    6. On the second page, click the arrow of the Data Source combo box and select Flat FileSource

    7. On the right side of File Name, click the Browse button

    8. Locate and select the Students.txt file you had saved

    9. Under Data Source, click Advanced

    10. As Column is selected, in the right list, click Name and type StudentID

    11. In the middle list, click each column and change its Name in the right column as follows:

    Column Name

    Column0 StudentID

    Column1 FirstName

    Column2 LastName

    Column3 DateOfBirth

    Column4 Gender

    Column5 Address

    Column6 City

    Column7 State

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (9 of 20)11/26/2008 5:23:36 PM

    http://functionx.com/sqlserver/Students.txthttp://functionx.com/sqlserver/Students.txt
  • 7/28/2019 Database Records

    10/20

    QL Server - Lesson 09: The Records of a Database

    Column8 ZIPCode

    Column9 HomePhone

    Column10 EmailAddress

    Column11 ParentsNames

    Column12 SPHome

    Column13 EmrgName

    Column14 EmrgPhone

    12. To see the list of columns, under Data Source, click Columns

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (10 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    11/20

    QL Server - Lesson 09: The Records of a Database

    13. Click Next 4 times

    14. Click Finish

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (11 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    12/20

    QL Server - Lesson 09: The Records of a Database

    15. Click Close

    16. Back in the Object Explorer, expand the ROSH and its Tables nodes.Right-click Students and click Design

    17. As the StudentID field is selected, press Tab and change its data type to int

    18. Press F6 and expand Identity Specification. Double-click (Is Identity) to set its value toYes

    19. Change the other columns as follows:

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (12 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    13/20

    QL Server - Lesson 09: The Records of a Database

    20. To save the table, click the Save button on the Standard toolbar:

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (13 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    14/20

    QL Server - Lesson 09: The Records of a Database

    21. When a Validation Warnings dialog box presents a few warnings, click Yes

    22. Close the table

    23. To view data stored on the table, in the Object Explorer, right-click dbo.Students and clickOpen Table

    hecking Records

    hecking the Existence of a Record

    One of the simplest operations a user can perform on a table consists of looking for a record.To do this, the user would open the table that contains the records and visually check them,ooking for a piece of information, such as a student's last name.

    As the database developer, you too can look for a record and there are various techniques youcan use. To assist you with this, Transact-SQL provides a function named EXISTS. Its syntaxs:

    T EXISTS(SELECT Something)

    This function takes one argument. The argument must be a SELECT statement that would beused to get the value whose existence would be checked. For example, in Lesson 2, we

    mentioned a system database names databases that contains a record of all databases storedon your server. You can use the EXISTS() function to check the existence of a certaindatabase. The formula you would use is:

    EXISTS (

    SELECT name

    FROM sys.databases

    WHERE name = N'DatabaseName'

    In the DatabaseName placeholder, you can enter the name of the database.

    electing Records

    Before 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:

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (14 of 20)11/26/2008 5:23:36 PM

    http://functionx.com/sqlserver/Lesson02.htm#databaseshttp://functionx.com/sqlserver/Lesson02.htm#databases
  • 7/28/2019 Database Records

    15/20

    QL Server - Lesson 09: The Records of a Database

    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.

    To 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.

    ecords Maintenance

    ntroduction

    Record maintenance includes viewing records, looking for one or more records, modifying oneor more records, or deleting one or more records.

    pdating a Record

    Updating a record consists of changing its value for a particular column. To update a recordusing SQL:

    q In the Object Explorer, you can right the table, position the mouse on Script Table As ->UPDATE To -> New Query Editor Window

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (15 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    16/20

    QL Server - Lesson 09: The Records of a Database

    q Open an empty query window and type your code

    To support record maintenance operations, the SQL provides the UPDATE keyword that isused to specify the table on which you want to maintain the record(s). The basic formula touse is:

    DATE TableName

    T ColumnName = Expression

    With 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:

    EATE DATABASE VideoCollection;

    E VideoCollection;

    EATE TABLE Videos (

    VideoID INT NOT NULL IDENTITY(1,1),

    VideoTitle varchar(120) NOT NULL,

    Director varchar(100) NULL,

    YearReleased SMALLINT,

    VideoLength varchar(30) NULL,Rating varchar(6)

    SERT INTO Videos(VideoTitle, Director, YearReleased, VideoLength)

    LUES('A Few Good Men','Rob Reiner',1992,'138 Minutes');

    SERT INTO Videos(VideoTitle, Director, YearReleased, VideoLength)

    LUES('The Silence of the Lambs','Jonathan Demme',1991,'118 Minutes');

    SERT INTO Videos(VideoTitle, Director, VideoLength)

    LUES('The Distinguished Gentleman', 'James Groeling', '112 Minutes');

    SERT INTO Videos(VideoTitle, Director, VideoLength)

    LUES('The Lady Killers', 'Joel Coen & Ethan Coen', '104 Minutes');

    SERT INTO Videos(VideoTitle, Director, VideoLength)

    LUES('Ghosts of Mississippi', 'Rob Reiner', '130 Minutes');

    pdating all Records

    Imagine that, at one time, on a particular table, all records need to receive a new value underone particular column or certain columns. There is no particular way to visually update allrecords of a table. You can just open the table to view its records, and then change them oneat a time.

    In SQL, the primary formula of the UPDATE statement as introduced on our formula can beused to update all records. Here is an example:

    E VideoCollection;

    DATE Videos

    T Rating = 'R';

    With this code, all records of the Videos table will have their Rating fields set to a value of R:

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (16 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    17/20

    QL Server - Lesson 09: The Records of a Database

    diting a Record

    Editing 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 thevalue is wrong, such as the Director of the the 'The Distinguished Gentleman' video of thistable:

    Video Title Director Year Length Rating

    A Few Good Men Rob Reiner 1992 138 Minutes R

    The Silence of the Lambs Jonathan Demme 1991 118 Minutes

    The Distinguished Gentleman James Groeling 112 Minutes RThe Lady Killers Joel Coen & Ethan Coen 104 Minutes R

    Ghosts of Mississippi Rob Reiner 130 Minutes

    To edit a record, first open the table to view its records. Locate the record, the column onwhich you want to work, and locate the value you want to change, then change it.

    In SQL, you must provide a way for the interpreter to locate the record. To do this, you wouldassociate the WHERE operator in an UPDATE statement using the following formula:

    DATE TableName

    T ColumnName = Expression

    ERE Condition(s)

    The WHERE operator allows you to specify how the particular record involved would bedentified. It is very important, in most cases, that the criterion used be able to uniquelydentify the record. In the above table, imagine that you ask the interpreter to change thereleased year to 1996 where the director of the video is Rob Reiner. The UPDATE statementwould be written as follows:

    DATE Videos

    T YearReleased = 1996

    ERE Director = 'Rob Reiner';

    In the above table, there are at least two videos directed by Rob Reiner. When this statements executed, all video records whose director is Rob Reiner would be changed, which wouldcompromise existing records that didn't need this change. This is where the identity column

    becomes valuable. We saw earlier that, when using it with the IDENTITY feature, thenterpreter appends a unique value to each record. You can then use that value to identify aparticular record because you are certain the value is unique.

    Here is an example used to specify the missing copyright year of a particular record:

    DATE Videos

    T YearReleased = 1996

    ERE VideoID = 5;

    Here is an example used to change the name of the director of a particular video:

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (17 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    18/20

    QL Server - Lesson 09: The Records of a Database

    DATE Videos

    T Director = 'Jonathan Lynn'

    ERE VideoTitle = 'The Distinguished Gentleman';

    emoving all Records

    If 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 selectall of 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.

    Using SQL, to clear a table of all records, use the DELETE operator with the following formula:

    LETE TableName;

    When this statement is executed, all records from the TableName factor would be removedfrom the table. Be careful when doing this because once the records have been deleted, youcannot get them back.

    emoving a Record

    If 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 delete a record using SQL:

    q In the Object Explorer, you can right the table, position the mouse on Script Table As ->DELETE To -> New Query Editor Window

    q Open an empty query window and type your code

    In SQL, to delete a record, use the DELETE FROM statement associate the WHERE operator.The formula to follow is:

    LETE FROM TableName

    ERE 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 a

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (18 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    19/20

    QL Server - Lesson 09: The Records of a Database

    criterion. 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:

    LETE FROM Videos

    ERE VideoTitle = 'The Lady Killers';

    Here is an example used to clear the table of all videos:

    LETE FROM Videos;

    Practical Learning: Ending the Lesson

    1. Close the query window without saving the file

    2. In the Object Explorer, under the Databases node, right-click WorldStatistics and clickDelete

    3. In the dialog box, click OK

    esson Summary

    opics Reviewed

    opics Reviews

    q Record

    q Row

    q Table Navigation

    q Visual Data Entry

    q SQL Data Entry

    q

    Adjacent Data Entryq Random Data Entry

    q Default Values

    q Identity Columns

    q Expressions

    q Check Constraints

    q Collation

    q Data Import

    q Selecting Records

    q Editing Records

    q Updating Records

    q Deleting Records

    eywords, Operators, and Properties

    q NULL

    q NOT NULL

    q DEFAULT

    q IDENTITY

    le:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (19 of 20)11/26/2008 5:23:36 PM

  • 7/28/2019 Database Records

    20/20

    QL Server - Lesson 09: The Records of a Database

    q Identity Specification

    q (Is Identity)

    q Identity Seed property

    q Identity Increment

    q CONSTRAINT

    q CHECK

    q Collation

    q databases

    q EXISTS

    q UPDATE

    q DELETE

    xercises

    tility Company

    1. In Microsoft SQL Server Management Studio, access the UtilityCompany1 database

    2. Open the Employees table and enter a few records

    EmployeeNumber FirstName LastName Title

    Robert Anson

    Justine Keys

    Edward Kirkland

    Kimberly Eisner

    Jonathan Adamson

    Steve Fox

    Andrew Boroughs

    3. Open the Customers table and create a few records

    AccountNumber DateAccountCreated CustomerName Address City State EmailAddress

    S States

    1. Get your research papers on US regions and their states

    2. Connect to the server from the Command Prompt and access the UnitedStatesRegions1 database

    3. Enter the names of the regions in the Regions table

    4. Enter the names of the states in the States table

    5. Exit the Command Prompt

    Previous Copyright 2007 FunctionX, Inc. Next

    http://functionx.com/sqlserver/Lesson08.htmhttp://functionx.com/sqlserver/index.htmhttp://functionx.com/sqlserver/Lesson10.htmhttp://functionx.com/sqlserver/Lesson10.htmhttp://functionx.com/sqlserver/index.htmhttp://functionx.com/sqlserver/Lesson08.htm