Database Records
Database Records
<a
In the Object Explorer, you can right the table, position the mouse on Script Table As -> INSERT To -> New Query Editor Window Open an empty query window and type your code
In the SQL, data entry is performed using the INSERT combined with the VALUES keywords. The primary statement uses the following syntax: INSERT TableName VALUES(Column1, Column2, Column_n);
Here is an example: INSERT Countries([Country Name],Capital,[Internet Code],Population,Area) VALUES('China', 'Beijing', 'cn', 1313973713, 9596960); GO Alternatively, you can use the INTO keyword between the INSERT keyword and the TableName factor: 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. Here is an example: INSERT INTO Countries VALUES('South Africa', 1219912, 44187637, 'Pretoria','za')
Binding, type the desired value following the rules of the column's data type: It the Data Type is Text-based (char, varchar, text, and their variants) Intructions Enter the value in single-quotes Enter the value as a number but following the rules of the data type. For example, if you enter a value higher than 255 for a tinyint, you would receive an error Enter 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 Control Panel (Regional Settings). Enter the value as 0 for FALSE or any other long integer value for TRUE
Numeric-based
Date or Time
Bit
After creating the table, the user does not have to provide a value for a column that has a default. If the user does not provide the value, the default would be used when the record is saved. If the user provides a value for a column that has a default value and then deletes the value, the default value rule would not apply anymore: The field would simply become empty
Identity Columns
Introduction
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 Women Boys Men Women Girls Women Long-sleeve jersey dress Iron-Free Pleated Khaki Pants Striped long-sleeve shirt Long-sleeve jersey dress Shoulder handbag Continental skirt Size S Unit Price 39.95
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 that name. This table happens to have two items with that name. You may then decide to look for an 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 don't have a good criterion you 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 column whose main purpose is to distinguish one record from another. To assist you with this, the SQL allows you to create a column whose data type is an integer type but the user doesn't have to enter data for that column. A value would automatically be entered into the field when a new record 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.
ItemID int IDENTITY(1, 1) NOT NULL, Category varchar(50), [Item Name] varchar(100) NOT NULL, Size varchar(20), [Unit Price] money); GO
Using Functions
In order to involve a function with your data entry, you must have and identity one. You can use one of the built-in functions of Transact-SQL. You can check one of the functions we reviewed in Lesson 7. Normally, the best way is to check the online documentation to find out if the assignment you want to perform is already created. Using a built-in function would space you the trouble of getting a function. For example, imagine you have a database named AutoRepairShop and imagine it has a table used to create repair orders for customers: CREATE TABLE RepairOrders ( RepairID int Identity(1,1) NOT NULL, CustomerName varchar(50), CustomerPhone varchar(20), RepairDate DateTime ); GO When performing data entry for this table, you can let the user enter the customer name and phone number. On the other hand, you can assist the user by programmatically entering the current date. To do this, you would call the GETDATE() function. Here are examples: INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate) VALUES('Annette Berceau', '301-988-4615', GETDATE()); GO INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate) VALUES('(240) 601-3795', 'Paulino Santiago', GETDATE()); GO INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone) VALUES('Alicia Katts', GETDATE(), '(301) 527-3095'); GO INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName) VALUES(GETDATE(), '703-927-4002', 'Bertrand Nguyen'); GO You can also involve the function in an operation, then use the result as the value to assign to a 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 your own, using the techniques we studied in Lesson 6.
Check Constraints
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (5 of 20)11/26/2008 5:23:36 PM
Introduction
When performing data entry, in some columns, even after indicating the types of values you expect the user to provide for a certain column, you may want to restrict a range of values that are 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 interpreter examines a value that has just been provided for a column. If the value is appropriate: 1. The constraint produces TRUE 2. 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.
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 of information that a check constraint should hold is the mechanism it would use to check its values. This is provided as an expression. Therefore, to create a constraint, you can click Expression and click its ellipsis button. This would open the Check Constraint Expression dialog box. 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 we studied already. Here is an example that will check that a new value specified for the Student Number is greater than 1000:
After creating the expression, you can click OK. If the expression is invalid, you would receive an error and given the opportunity to correct it. You can create as many check constraints as you judge necessary for your table:
It is important to understand that a check constraint it neither an expression nor a function. A check 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 Server Management Studio, inside the table's node, there is a node named Constraints and, if you expand 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 invalid value, an error would display. Here is an example:
Instead of an expression that uses only the regular operators, you can use a function to assist in the checking process. You can create and use your own function or you can use one of the built-in Transact-SQL functions.
Collation
Because different languages use different mechanisms in their alphabetic characters, this can affect the way some sort algorithms or queries are performed on data, you can ask the database to apply a certain language mechanism to the field by changing the Collation property. Otherwise, you should accept the default specified by the table.
Data Import
Another technique used to get data into one or more tables consists of importing already existing data from another database or from any other recognizable data file. Microsoft SQL Server provides various techniques and means of importing data. The easiest type of data that can be imported into SQL Server, and which is available on almost all database environments, is the text file. Almost every database environment allows you 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 character that serves as a separator. This separator can be the single-quote, the double-quote, or any valid character. Data between the quotes is considered as belonging to a distinct field. Besides this 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 is to distinguish each record from another. This is easily taken car of by the end of line of a record. This is also recognized as the carriage return. These directives can help you manually create a text file that can be imported into Microsoft SQL Server. In practicality, if you want to import data that resides on another database, you can ask that application to create the source of data. Most applications can do that and format the data. That is the case for the data we will use in the next exercise: it is data that resided on a 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.
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 New Database... 3. Type ROSH and press Enter 4. In the Object Explorer, right-click ROSH, position the mouse on Tasks and click Import Data 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 File Source 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 Column0 Column1 Column2 Column3 Column4 Column5 Column6 Column7 Name StudentID FirstName LastName DateOfBirth Gender Address City State
12. To see the list of columns, under Data Source, click Columns
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 to Yes 19. Change the other columns as follows:
20. To save the table, click the Save button on the Standard toolbar:
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 click Open Table
Checking Records
Checking 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, looking 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 you can use. To assist you with this, Transact-SQL provides a function named EXISTS. Its syntax is: BIT EXISTS(SELECT Something) This function takes one argument. The argument must be a SELECT statement that would be used 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 stored on your server. You can use the EXISTS() function to check the existence of a certain database. The formula you would use is: IF EXISTS ( SELECT name FROM sys.databases WHERE name = N'DatabaseName' ) In the DatabaseName placeholder, you can enter the name of the database.
Selecting Records
Before visually performing some operations on a table, you must first select one or more records. In the Table window, to select one record, position the mouse on the left button of the record and click:
To select a range of records, click the gray button of one of the records, press and hold Shift, then click the gray button of the record at the other extreme. To select the records in a random fashion, select one record, press and hold Ctrl, then click the gray 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 the Object Explorer and click Open Table) to view its records. Locate the record and the field you want to work on and perform the desired operation.
Records Maintenance
Introduction
Record maintenance includes viewing records, looking for one or more records, modifying one or more records, or deleting one or more records.
Updating a Record
Updating a record consists of changing its value for a particular column. To update a record using SQL:
q
In the Object Explorer, you can right the table, position the mouse on Script Table As -> UPDATE To -> New Query Editor Window
To support record maintenance operations, the SQL provides the UPDATE keyword that is used to specify the table on which you want to maintain the record(s). The basic formula to use is: UPDATE TableName SET ColumnName = Expression With this formula, you must specify the name of the involved table as the TableName factor of our formula. The SET statement allows you to specify a new value, Expression, for the field under the ColumnName column. Consider the following code to create a new database named VideoCollection and to add a table named Videos to it: CREATE DATABASE VideoCollection; GO USE VideoCollection; GO CREATE 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) ); GO INSERT INTO Videos(VideoTitle, Director, YearReleased, VideoLength) VALUES('A Few Good Men','Rob Reiner',1992,'138 Minutes'); INSERT INTO Videos(VideoTitle, Director, YearReleased, VideoLength) VALUES('The Silence of the Lambs','Jonathan Demme',1991,'118 Minutes'); INSERT INTO Videos(VideoTitle, Director, VideoLength) VALUES('The Distinguished Gentleman', 'James Groeling', '112 Minutes'); INSERT INTO Videos(VideoTitle, Director, VideoLength) VALUES('The Lady Killers', 'Joel Coen & Ethan Coen', '104 Minutes'); INSERT INTO Videos(VideoTitle, Director, VideoLength) VALUES('Ghosts of Mississippi', 'Rob Reiner', '130 Minutes'); GO
Editing a Record
Editing a record consists of changing a value in a field. It could be that the field is empty, such as the Year of the the 'The Lady Killers' video of the following table. It could be that the value is wrong, such as the Director of the the 'The Distinguished Gentleman' video of this table: Video Title A Few Good Men The Silence of the Lambs The Distinguished Gentleman The Lady Killers Ghosts of Mississippi Director Rob Reiner Jonathan Demme James Groeling Joel Coen & Ethan Coen Rob Reiner Year 1992 1991 Length 138 Minutes 118 Minutes 112 Minutes 104 Minutes 130 Minutes R R Rating R
To edit a record, first open the table to view its records. Locate the record, the column on which 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 would associate the WHERE operator in an UPDATE statement using the following formula: UPDATE TableName SET ColumnName = Expression WHERE Condition(s) The WHERE operator allows you to specify how the particular record involved would be identified. It is very important, in most cases, that the criterion used be able to uniquely identify the record. In the above table, imagine that you ask the interpreter to change the released year to 1996 where the director of the video is Rob Reiner. The UPDATE statement would be written as follows: UPDATE Videos SET YearReleased = 1996 WHERE Director = 'Rob Reiner'; In the above table, there are at least two videos directed by Rob Reiner. When this statement is executed, all video records whose director is Rob Reiner would be changed, which would compromise 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, the interpreter appends a unique value to each record. You can then use that value to identify a particular record because you are certain the value is unique. Here is an example used to specify the missing copyright year of a particular record: UPDATE Videos SET YearReleased = 1996 WHERE VideoID = 5; GO Here is an example used to change the name of the director of a particular video:
UPDATE Videos SET Director = 'Jonathan Lynn' WHERE VideoTitle = 'The Distinguished Gentleman';
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: DELETE TableName; When this statement is executed, all records from the TableName factor would be removed from the table. Be careful when doing this because once the records have been deleted, you cannot get them back.
Removing a Record
If you find out that a record is not necessary, not anymore, or is misplaced, you can remove it from 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 confirm your 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 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: DELETE FROM TableName WHERE 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
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/insert.htm (18 of 20)11/26/2008 5:23:36 PM
criterion. Once again, make sure you are precise in your criteria so you would not delete the wrong record(s). Here is an example used to remove a particular record from the table: DELETE FROM Videos WHERE VideoTitle = 'The Lady Killers'; Here is an example used to clear the table of all videos: DELETE FROM Videos;
Lesson Summary
Topics Reviewed Topics Reviews
Record Row Table Navigation Visual Data Entry SQL Data Entry Adjacent Data Entry Random Data Entry Default Values Identity Columns Expressions Check Constraints Collation Data Import Selecting Records Editing Records Updating Records Deleting Records
Identity Specification (Is Identity) Identity Seed property Identity Increment CONSTRAINT CHECK Collation databases EXISTS UPDATE DELETE
3. Open the Customers table and create a few records AccountNumber DateAccountCreated CustomerName Address City State EmailAddress
US 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
Next