Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 53 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
53
Dung lượng
2,24 MB
Nội dung
242 CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 16. Similar to when we produced a script for the database, clicking next brings up a summary of what will be performed within the plan (see Figure 7-37). Here you can review what will be completed, and with the number of different options that will be performed, it is a good place to complete a double check. Clicking Finish will produce the maintenance plan itself. Figure 7-37. Completing the plan 17. It is possible to execute the plan outside of the maintenance plan schedule. The maintenance plan created previously can now be found under the Management/Maintenance Plan nodes in the Object Explorer. Right-click the nodes to bring up the pop-up menu shown in Figure 7-38. Selecting Execute will start the plan immediately. Do so now. Figure 7-38. Maintenance plan pop-up menu 18. While the plan is executing, the dialog box shown in Figure 7-39 will be displayed. 19. Once the plan is executed along with any additional plans, a log is kept to allow you to check how they progressed. In Figure 7-40, you see that there is a circle with a cross in it, which should appear red on your screen, denoting that the plan had an error. By clicking that particular plan, it is possible to see what the error was. Dewson_5882C07.fm Page 242 Monday, January 9, 2006 3:27 PM CHAPTER 7 ■ DATABASE BACKUPS, RECOVERY, AND MAINTENANCE 243 Figure 7-39. Maintenance plan executing Figure 7-40. Maintenance plan log Summary You have seen a great deal in this chapter that is crucial to ensuring that your database is always secure if there are any unforeseen problems. As a manager drummed into me, the unex- pected will always happen, but you must always be able to recover from it, no matter what. Therefore, regular backups that are known to work and even the occasional “disaster recovery test” should be done to ensure that you can restore when something unexpected happens. No matter what your managing director says, it is the data of a company that is its most important asset, not the people. Without the data, a company cannot function. If you cannot ensure that the data will be there, then the company is in a very dangerous position. Dewson_5882C07.fm Page 243 Monday, January 9, 2006 3:27 PM Dewson_5882C07.fm Page 244 Monday, January 9, 2006 3:27 PM 245 ■ ■ ■ CHAPTER 8 Working with the Data We have now built our tables, set up the relationships, and backed up our solution, so we are ready to start inserting our data. The many tables within the database cover a number of different types of data that can be stored, ranging from characters and numbers through to images and XML. This chapter will show you how to insert data into columns defined with all of these data types. Not all the tables will be populated with data at this point. We will insert data in other tables later on in the book when different functionality of SQL Server is being demonstrated. Although data is being inserted, the database is still at the stage of being set up, as we are inserting static information at this point in the examples we are building together. To clarify, static data is data that will not change once it has been set up, although there may be further additions to this data at periodic intervals such as when a new share is created. Not everyone who is allowed to access our database may, or should, be allowed to insert data directly into all of the tables. Therefore, you need to know how to set up the security to grant permission to specific user logins for inserting the data. The only people who really ought to be adding data directly to tables rather than using controlled methods such as stored proce- dures in production, for example, are special accounts like dbo accounts. In development, any developer should be able to insert data, but any login who would be testing out the application would not have that authority. You will see the reasons for this when we look at the security of adding data later in this chapter, and you will learn about alternative and more secure methods when we look at stored procedures and views. Once we have set up users correctly, it is time to demonstrate inserting data into SQL Server. It is possible to insert data using SQL commands through Query Editor or through SQL Server Management Studio. Although both of these tools will have the same final effect on the database, each works in its own unique way. When inserting data, you don’t have to insert data into every column necessarily. We take a look at when it is mandatory and when it is not. There are many different ways to avoid inserting data into every column. This chapter will demonstrate the various different methods you can use to avoid having to use NULL values and default values. By using these methods, you are reducing the amount of information it is necessary to include with a record insertion. This method of inserting data uses special commands within SQL Server called constraints. You will see how to build a column constraint through T-SQL in Query Editor as well as in SQL Server Management Studio. Dewson_5882C08.fm Page 245 Wednesday, January 4, 2006 3:43 PM 246 CHAPTER 8 ■ WORKING WITH THE DATA The T-SQL INSERT Command Syntax Before it is possible to insert data using T-SQL code, you need to be familiar with the INSERT command and its structure. The INSERT command is very simple and straightforward in its most minimal form, which is all that is required to insert a record. INSERT [INTO] {table_name|view_name} [{(column_name,column_name, )}] {VALUES (expression, expression, )} Obviously, we are required to start the command with the type of action we are trying to perform, for example, insert data. The next part of the command, INTO, is optional. It serves no purpose, but you will find some do use it to ensure their command is more readable. The next part of the statement deals with naming the table or the view that the insertion has to place the data into. If the name of the table or view is the same as that of a reserved word or contains spaces, we have to surround that name with square brackets or double quotation marks. However, it is better to use square brackets, because there will be times you wish to set a value such as Acme’s Rockets to a column data, which can be added easily by surrounding it by double quotation marks, as covered in the discussion of SET QUOTED_IDENTIFIER OFF earlier in the book. I cannot stress enough that really, there is nothing to be gained by using reserved words for table, views, or column names. Deciding on easy-to-use and unambiguous object names is part of a good design. Column names are optional, but it is best practice to list them to help to have reliable code, as this ensures that data is only inserted into the columns into which you want it to be inserted. Therefore, it will be necessary to place the column names in a comma-delimited list. The list of column names must be surrounded by parentheses, (). The only time that column names are not required is when the INSERT statement is inserting data into every column that is within the table in the same order as they are laid out in the table. However, this is a potentially dangerous scenario. If you build an INSERT command which you then saved and used later, you expect the columns to be in a specific order because that is the way they have always been. If someone then comes along and adds a new column, or perhaps alters the order, your query or stored procedure will either not work or give erroneous results, as values will be added to the wrong columns. Therefore, I recommend that you always name every column in anything but a query, which is built, run once, and thrown away. The VALUES keyword, which precedes the actual values to be entered, is mandatory. SQL Server needs to know that the following list is a list of values, and not a list of columns. There- fore, you have to use the VALUES keyword, especially if you omit the list of columns as explained previously. Finally, you will have a comma-separated list surrounded by parentheses covering the values of data to insert. There has to be a column name for every value to be entered. To clarify, if there are ten columns listed for data to be entered, then there must be ten values to enter. Now that the INSERT command is clear, time to move on and use it. Dewson_5882C08.fm Page 246 Wednesday, January 4, 2006 3:43 PM CHAPTER 8 ■ WORKING WITH THE DATA 247 INSERT SQL Command The first method of inserting data is to use the INSERT SQL command as described previously. This example will insert one record into the ShareDetails.Shares table using Query Editor. When inserting the data, the record will be inserted immediately without any opportunity to roll back changes. This command does not use any transaction processing to allow any changes to take place. You will also see with this example how Query Editor can aid you as a developer in building the SQL command for inserting a record. Let’s dive straight in and create the record. Try It Out: Query Editor Scripting 1. Ensure that you have a Query Editor window open, connected to our ApressFinancial database, and that you are logged in with an account that has insert permissions on the ShareDetails.Shares table (this will be any member of the administrator’s or database owner’s role). 2. Right-click against the ShareDetails.Shares table, select Script Table As ➤ INSERT To ➤ New Query Editor Window. 3. This will bring up the following code. SQL Server covers itself concerning the use of reserved words, spaces in names, etc., by surrounding every object name with square brackets. It also fully qualifies the table name with the database name and schema owner, in this case, ShareDetails. Moving to the values, you can see the column name repeated so that when altering the values, if the table has a large number of columns, you know which column you are working with. The final part in the jigsaw is an indication to the data type and length to aid you as well. INSERT INTO [ApressFinancial].[ShareDetails].[Shares] ([ShareDesc] ,[ShareTickerId] ,[CurrentPrice]) VALUES (<ShareDesc, nvarchar(50),> ,<ShareTickerId, nvarchar(50),> ,<CurrentPrice, numeric,>) 4. We need to place a modification at the top of this code, just to ensure that Query Editor has a setting to allow double quotes to be used to surround strings. This was covered in Chapter 5 when discussing database options. To cover yourself though, you can always place the following code at the start of queries where quotation marks will be used. There is one hidden downfall that will be covered at the end. Notice as well that a GO command is included at the end of the SET command. This is because this command must take place in its own transaction. SET QUOTED_IDENTIFIER OFF GO 5. By altering the code within the Query Editor pane, you will see that the next section of code actually inserts the data into the ShareDetails.Shares table. Notice that no GO statement is included at the end of this code. It is not necessary because there is only one INSERT and no other commands that need to form part of this same transaction. Dewson_5882C08.fm Page 247 Wednesday, January 4, 2006 3:43 PM 248 CHAPTER 8 ■ WORKING WITH THE DATA SET QUOTED_IDENTIFIER OFF GO INSERT INTO [ApressFinancial].[ShareDetails].[Shares] ([ShareDesc] ,[ShareTickerId] ,[CurrentPrice]) VALUES ("ACME'S HOMEBAKE COOKIES INC", 'AHCI', 2.34125) 6. Now that all the information has been entered into the Query Editor pane, it is time to execute the code. Press F5 or Ctrl+E, or click the execute button on the toolbar. You should then see the following result, which indicates that there has been one row of data inserted into the table. (1 row(s) affected) This now sees the first record of information placed into the database in the ShareDetails.Shares table. It is simple and straightforward. All the columns have been listed and a value has been inserted. Because the name had a single quotation mark within it, it is simpler to surround the name with double quotation marks. However, to make sure that this string was not seen as an identifier, we have to switch that option off. SQL Server Management Studio has the ability to create template scripts for several T-SQL commands. Templates, which you saw earlier in the book, hold parameter placeholders that require modification to build up the whole command. Template scripts differ from actual templates, as the information created within Query Editor for these templates is for one command only. Therefore, what you are actually seeing is the template for a one-line script. When using the scripting options within Query Editor, it is possible to build the script as you have just seen for inserting a record into the ShareDetails.Shares table, and save the T-SQL within a new Query Editor pane, to a file, or even to a clipboard. This would then allow the data to be reinserted instantaneously should the table be deleted. To an extent, scripting to files or a clipboard is not as useful as scripting to a Query Editor pane. By scripting to files or a clipboard, you would need to move back into these files to make the necessary changes for data insertion. As you saw, when the script is placed in the Query Editor pane, the table and the columns are listed, but obviously the values need to be altered. This would have to be completed in a file or a clipboard by reopening these contents and making modifications after the event. The scripting template does build the whole INSERT command and lists all the columns as well as—in the VALUES section of the command—the name of the column and its data type definition. From there, it is easier to know what value is expected within the INSERT command line. The example mentions that using SET QUOTED_IDENTIFIER OFF does have one hidden downfall: In many cases, when using T-SQL commands, it is possible to surround reserved words with double quotation marks, rather than square brackets; however, with the QUOTED_IDENTIFIER set to OFF, you will only be able to surround reserved words with square brackets. If you had QUOTED_IDENTIFIER set to ON, then you could not have put ACME'S in the name; the code would have to have been written with two single quotation marks. Therefore, the code would have had to look like the following: Dewson_5882C08.fm Page 248 Wednesday, January 4, 2006 3:43 PM CHAPTER 8 ■ WORKING WITH THE DATA 249 INSERT INTO [ApressFinancial].[ShareDetails].[Shares] ([ShareDesc] ,[ShareTickerId] ,[CurrentPrice]) VALUES ('ACME''S HOMEBAKE COOKIES INC', 'AHCI', 2.34125) Now that you know how to construct an INSERT statement, it is time to look at how you need not define all the columns within a table. It is not always necessary to define columns with a value when inserting rows of data. This next section looks at two of these methods: the use of default values and allowing a NULL value. As you have just seen in our first examples, we specified every column in the table within the INSERT statement. You are now probably wondering whether you have to specify every column every time a record is inserted into a table. The answer is no. However, there are a few areas to be aware of. Default Values The first method for avoiding having to enter a value is to set a column or a set of columns with a default value. We set up the CustomerDetails.Customers table to have a default value when creating the tables in Chapter 5. Default values are used when a large number of INSERTs for a column would have the same value entered each time. Why have the overhead of passing this information, which would be the column name plus the value, through to SQL Server, when SQL Server can perform the task quickly and simply for you? Network traffic would be reduced and accuracy ensured as the column information would be completed directly by SQL Server. Although it has been indicated that default values are best for a large number of INSERTs, it can also be argued that this need not be the case. Some people feel that all that is required is a significant number of rows to be affected from a default value setting for the use of default values to be an advantage. It does come down to personal preference as to when you think setting a default value will be of benefit. However, if there are times when you wish a column to have an initial value when a row is inserted with a specific value, then it is best to use a default value. The example in next section, where we build up our next set of INSERT statements, I will demonstrate how a default value will populate specific columns. When creating the CustomerDetails.Customers table, we created a column that is set up to be populated with a default value: the DateAdded column. In this column, we call a SQL Server reserved function, GETDATE(). This function gets the date and time from the operating system and returns it to SQL Server. By having this within a column default value, it is then inserted into a record when a row is added. Using NULL Values The next method for avoiding having to fill in data for every column is to allow NULL values in the columns. We did this for some columns when defining the tables. Ensuring that each Dewson_5882C08.fm Page 249 Wednesday, January 4, 2006 3:43 PM 250 CHAPTER 8 ■ WORKING WITH THE DATA column’s Allow Nulls option is checked can ensure this is true for all our columns. If you take a look at Figure 8-1, one of the columns in the ShareDetails.Shares table, ShareTickerId, does allow a NULL value to be entered into the column. Figure 8-1. NULLs selected on a column Therefore, the previous example could have placed data only in the ShareDesc and CurrentPrice fields if we’d wanted, as ShareId is an IDENTITY column and is auto-filled. If the ShareDetails.Shares record had only been inserted with those two columns, the command would have looked like the following T-SQL: INSERT INTO [ApressFinancial].[ShareDetails].[Shares] ([ShareDesc] ,[CurrentPrice]) VALUES ("ACME'S HOMEBAKE COOKIES INC", 2.34125) Figure 8-2 shows what the data would have looked like had we used the preceding T-SQL instead of the code in the previous section. Figure 8-2. Insert with NULL To see the same result as in Figure 8-2, you would view this table in SQL Server Management Studio. This is covered shortly, as unfortunately we are in the chicken-and-egg scenario of showing an area before it has been discussed. As you can see, the columns that had no data entered have a setting of NULL. A NULL setting is a special setting for a column. The value of NULL requires special handling within SQL Server or applications that will be viewing this data. What this value actually means is that the information within the column is unknown; it is not a numeric or an alphanumeric value. Therefore, because you don’t know if it is numeric or alphanumeric, you cannot compare the value of a column that has a setting of NULL to the value of any other column, and this includes another NULL column. ■Note One major rule involving NULL values: a primary key cannot contain any NULL values. Dewson_5882C08.fm Page 250 Wednesday, January 4, 2006 3:43 PM CHAPTER 8 ■ WORKING WITH THE DATA 251 Try It Out: NULL Values and SQL Server Management Studio Compared to T-SQL 1. Ensure that SQL Server Management Studio is running and that you are logged in with an account that allows the insertion of records. Any of our users can do this. 2. Expand the ApressFinancial node in the Object Explorer so you can see the CustomerDetails.Customers table. Right-click this table and select Open Table. 3. In the main pane on the right, you should now see a grid similar to Figure 8-3. This grid would usually show all the rows of data that are within the table, but as this table contains no data, the grid is empty and ready for the first record to be entered. Notice that on the far left-hand side appears a star. It will change to an arrow shortly. This is the record marker and denotes which record the grid is actually pointing to and working with for insertion. The arrow denotes which record you are viewing, and when the marker changes to a pencil, it denotes that you are writing data in that row, ready for updating the table. Perhaps not so relevant this instance, but very useful when several records are displayed. Figure 8-3. No data held within the table 4. It is a simple process to enter the information into the necessary columns as required. However, if you don’t enter the data into the correct columns, or leave a column empty when in fact it should have data, you will receive an error message. The first column, CustomerId, is protected, as this is an IDENTITY column, but if you enter Mr into the CustomerTitleId column, then you will see something similar to the message shown in Figure 8-4 when moving to another cell. This message is informing you that CustomerTitleId is expecting an integer data type and that what was entered was not of that type. Figure 8-4. Invalid data type 5. Now press the down arrow, after altering CustomerTitleId to the correct data type, to indicate that you have finished creating this customer and wish to create the next. This of course means that some columns that have to be populated aren’t, and SQL Server tells me so, as you see in Figure 8-5. I wanted to create a row that was full of NULL values, but I can’t. The error message indicates that CustomerFirstName has not been set up to allow a NULL value, and we need to put some data in there. Dewson_5882C08.fm Page 251 Wednesday, January 4, 2006 3:43 PM [...]... DELETE FROM CustomerDetails.Customers DBCC CHECKIDENT('CustomerDetails.Customers',RESEED,0) INSERT INTO CustomerDetails.Customers (CustomerTitleId,CustomerFirstName,CustomerOtherInitials, CustomerLastName,AddressId,AccountNumber,AccountTypeId, ClearedBalance,UnclearedBalance) VALUES (1,'Vic',NULL,'McGlynn',111,8 761 2311,1,4311.22,213.11) INSERT INTO CustomerDetails.Customers (CustomerTitleId,CustomerLastName,CustomerFirstName,... statements INSERT INTO CustomerDetails.Customers (CustomerTitleId,CustomerFirstName,CustomerOtherInitials, CustomerLastName,AddressId,AccountNumber,AccountTypeId, ClearedBalance,UnclearedBalance) VALUES (3,'Bernie','I','McGee',314 ,65 368 765 ,1 ,66 53.11,0.00) GO INSERT INTO CustomerDetails.Customers (CustomerTitleId,CustomerFirstName,CustomerOtherInitials, CustomerLastName,AddressId,AccountNumber,AccountTypeId,... SQL to change the results grid to return just three rows of data, as shown in Figure 8-18 Figure 8-18 Three rows returned 9 Again, by clicking the SQL button on the toolbar, the SQL code is exposed Notice how this differs from the previous example in that TOP (3) has been placed after the SELECT statement SELECT FROM TOP (3) * CustomerDetails.Customers So now that you know how to return data from SQL. .. (2,'Julie','A','Dewson',2134,8 162 5422,1,53.32,-12.21) GO Dewson_5882C08.fm Page 263 Wednesday, January 4, 20 06 3:43 PM CHAPTER 8 ■ WORKING WITH THE DATA INSERT INTO CustomerDetails.Customers (CustomerTitleId,CustomerFirstName,CustomerOtherInitials, CustomerLastName,AddressId,AccountNumber,AccountTypeId, ClearedBalance,UnclearedBalance) VALUES (1,'Kirsty',NULL,'Hull',4312, 965 65334,1,1 266 .00,10.32) 2 Now just... even when you want to return specific rows, using SQL Server Management Studio makes this whole task very easy This first example will demonstrate how flexible SQL Server Management Studio is in retrieving all the data from the CustomerDetails.Customers table Try It Out: Retrieving Data Within SQL Server Management Studio 1 Ensure that SQL Server Management Studio is running Navigate to the ApressFinancial... In this instance from the CustomerDetails.Customers table, we would like to return a customer’s first name, last name, and the current account balances This would mean naming CustomerFirstName, CustomerLastName, and ClearedBalance as the column names in the query The code will read as follows: SELECT CustomerFirstName,CustomerLastName,ClearedBalance FROM CustomerDetails.Customers 269 Dewson_5882C08.fm... data from SQL Server Management Studio, let’s look at using T -SQL and probably the T -SQL statement you will use most often: the SELECT The SELECT Statement If we wish to retrieve data for viewing from SQL Server using T -SQL commands, then the SELECT statement is the command we need to use This is quite a powerful command, as it can retrieve data in any order, from any number of columns, from any table... set Or if you are using a tool such as Crystal Reports to display data from a SELECT statement within a SQL Server stored procedure, then naming the columns would help there as well The column names are less user friendly, and some column names will also be confusing for users; therefore, it would be ideal to be able to alter the names of the column headings Replacing the SQL Server column headings with... January 4, 20 06 3:43 PM 258 CHAPTER 8 ■ WORKING WITH THE DATA 6 Another method is to move to SQL Server Management Studio, find the CustomerDetails CustomerProducts table, right-click it, and select Modify This brings us into the Table Designer, where we can navigate to the necessary column to check out the default value, in this case Renewable Also notice the yellow key against the CustomerFinancialProductId... stretches out the display, but from here we can see easily how large each column is supposed to be Figure 8-23 Results as text 4 There will be times, though, when users require output to be sent to them For example, they may wish to know specific details from a set of records, and so you build a query and save the results to a file to send to them Or perhaps they want output to perform some analysis of data . section. DELETE FROM CustomerDetails.Customers DBCC CHECKIDENT('CustomerDetails.Customers',RESEED,0) INSERT INTO CustomerDetails.Customers (CustomerTitleId,CustomerFirstName,CustomerOtherInitials, CustomerLastName,AddressId,AccountNumber,AccountTypeId, ClearedBalance,UnclearedBalance) VALUES. stored procedures and views. Once we have set up users correctly, it is time to demonstrate inserting data into SQL Server. It is possible to insert data using SQL commands through Query Editor. practice to list them to help to have reliable code, as this ensures that data is only inserted into the columns into which you want it to be inserted. Therefore, it will be necessary to place