SQL 2000 Tutorial

Embed Size (px)

Citation preview

  • 8/6/2019 SQL 2000 Tutorial

    1/65

    SQL Server provides an effective method for adding users in SQL Server and for managingdata and information so that it can easily be stored and retrieved from the underlying files inorder to provide the functionality it is designed for.

    Once the database is designed, configured and implemented, it is critical that you startadding users in SQL Server so that people needing access to the data or specific bits ofdata be granted access to what they need to be able to access.

    This is increasingly important as the need for more secure practices, guidelines and policiesbecomes a greater force in the workplace. Security has become more prevalent in the day-to-day operations of practically every organization in the world.

    So how can SQL Server and its built in security allow for a more secure organization andhelp to protect the data that we are trying to guard?

    Working with SQL Server and the security it has within it is a critical component of databaseadministration. Adding users in SQL Server is an important task.

    When adding users in SQL Server, it provides three methods of authenticating users withinthe database that can be implemented in order to control how users are granted access tothe database.

    These three methods are windows authentication, SQL Server authentication and mixed-mode authentication.

    Windows authentication performs a check of the user credentials with a network validationto ensure that the user has access to the resource.

    SQL Server authentication requires a valid SQL Server login name and passwordcombination to validate the user access against the database before granting access to theresources on the server.

    Mixed mode security will allow the user to connect to the database via a valid Windowsaccount or through a valid SQL Server login. The type of security you implement dependson the type of security architecture you decide is best for your specific needs on the serverand the network.

    In order to configure security in SQL Server, the administrator may have to use not onlytools within SQL Server but must also work with network accounts in order to grant accessand adding users in SQL Server correctly.

    In order to view the logins that are used and defined within SQL Server using EnterpriseManager, select the Security node within Enterprise Manager. The Logins node withinSecurity will allow you to view the logins defined within that database.

    The illustration below shows the screen and the information that it will provide anyone wholooks at it.

  • 8/6/2019 SQL 2000 Tutorial

    2/65

    The first column is the name of the login as it is known by the database. The type column isnext and depicts what type of login it happens to be within the database.

    The following column tells whether or not the login has access to the server. This is theServer Access column.

    The next two columns deal with default settings for the user within the server. Thesesettings deal with the database that serves as the default database for that login and thedefault language that is associated with that account.

    In order to edit a login in SQL Server double-click on the login or right click and selectProperties. Doing so will bring up the following dialog:

  • 8/6/2019 SQL 2000 Tutorial

    3/65

    The General tab deals with the type of authentication to use for the login as well as settingthe default database and language for that login.

    If Windows authentication is chosen, a domain must be selected and then the securityaccess should be either granted or denied to the login.

    If SQL Server authentication is chosen, the password should be entered. Click OK to saveany changes. The dialog also contains a tab to allow the administrator to define the serverroles for the login (Server Roles).

    The following illustration shows this tab:

  • 8/6/2019 SQL 2000 Tutorial

    4/65

    The server roles can be selected and then click OK to save the changes. Each role hasspecific rights within the server and in order to understand what the login should be

    associated with, the roles should be understood by those assigning them.

    The final tab on the dialog is the Database Access tab. The following illustration shows thistab:

  • 8/6/2019 SQL 2000 Tutorial

    5/65

    This tab will allow the administrator to select each database within the SQL Server andspecify the database roles within that database.

    These roles can grant and/or deny various capabilities within the databases for thatparticular login. Some examples of these roles include a data writer role, which will allow theuser to update and insert data into the database and a data reader roles that allows theuser to query the database in order to view the data.

    Users can also be added to individual databases by expanding the database in questionand then selecting the Users node. The following illustration shows this screen:

  • 8/6/2019 SQL 2000 Tutorial

    6/65

    In order to access the properties for a particular user, double click that user or right clickand select Properties from the popup menu. This will bring up the following dialog in orderto manage the permissions assigned to that particular user account.

  • 8/6/2019 SQL 2000 Tutorial

    7/65

    The Permissions button will bring up the dialog to allow the administrator to grant or allowaccess to specific objects within the database. The following dialog shows this portion of theprocess:

  • 8/6/2019 SQL 2000 Tutorial

    8/65

    By selecting and deselecting specific options within this dialog, the administrator can assignand deny access to certain objects within the database.

    Different object types will have different operations that can be executed against them as

    can be seen in the illustration above.

    For example, tables and views can have Select, Insert, Update, Delete and others whilestored procedures do not have these operations.

    The Columns button applies to views and tables and can be used to control what columnsthat user has access to within the database.

    This level of control can help to make a database extremely secure, but can cause issuesfor those who are not familiar with the security that has been architected for a particulardatabase or a server. Once the changes have been made to the user, they can be saved byclicking the Apply button.

    Hopefully, you now have a better understanding of how to adding users in SQL Server andhow to work with security within SQL Server, as well as setting up a secure databaseenvironment in order to protect your data and your information that can prove to be vital tothe success of your business.

  • 8/6/2019 SQL 2000 Tutorial

    9/65

    Moving Database

    If you need moving the database to another location, the attach and detach functionality isindispensable.

    As many of you may or may not know, SQL Server is a database management system usedto store data and objects needed to work with that data.

    It is one of many products on the market designed for this purpose. SQL Server works byallowing the user to specify a location on the physical drives accessible by the server andproviding the engine needed to store, retrieve, organize and utilize the data and objectswithin the database.

    The database is stored in files on hard drives that are accessed in order to gain access tothe contents of the database. The files associated with a database have a default location,but upon database creation, they can be configured to go to another location.

    This allows for data to be better configured and organized across hard drives that may havelimited space available for data storage. What happens however, when a file needs to beincorporated into the database management system from an external source?

    This is where the concept of moving the database by attaching and detaching comes intoplay.

    When a database is used and managed by SQL Server, the data files on the hard drivesassociated with that database are locked to use by any other application.

    If you try to access that file, a message will alert you to the fact that the file is being used byanother application and you cannot access it. This makes the possibility of moving adatabase from one location to another or copying the database for use by another agencyout of the question.

    For example, if you were traveling to another location to work on an application and you hadto work from a machine that did not have access to that database, you could take a copy ofthe database to use to work with.

    This is where the ability to attach and detach a database will come into play. You candetach a database in order to remove it from the control of SQL Server and enable the filesto be accessed by external methods or applications.

    This is where the concept of detaching a database can be used. By detaching a database itcan be copied and moved to another location without interference from the SQL Servermanaging that database.

    Detaching a database in Enterprise Manager can be accomplished by the following:

    1. Right-click on the database in question. This will bring up menu options shown below:

  • 8/6/2019 SQL 2000 Tutorial

    10/65

    After brining up the menu options, go to the Detach Database option under the All Tasksmenu option as illustrated below:

    Select the Detach Database option to begin detaching the database from the databasemanagement system. After selecting the Detach Database option the following screen will

    appear to confirm the detach operation:

  • 8/6/2019 SQL 2000 Tutorial

    11/65

    This screen informs the user of the number of active connections to the database.

    This can be helpful so that users of the database can be informed that the database theyare using is getting ready to become unavailable so that they can save the work that theyare working on help you determine a better schedule for the when the detachment operationcan occur.

    The screen also shows whether or not the database is being used in replication andwhether the database is ready to be detached.

    If you would like to update the statistics for the database prior to detaching it, the option canbe selected.

    To proceed with the detachment of the database click the OK button. To cancel theoperation, click the Cancel button. The detaching of the database is confirmed with thefollowing dialog box:

  • 8/6/2019 SQL 2000 Tutorial

    12/65

    The database can also be detached from the database management system using QueryAnalyzer and the Transact-SQL language. To do so, open a session in Query Analyzer andenter the sp_detach_db command. The syntax for the command is as follows:

    sp_detach_db 'dbname' ,'skipchecks' ]

    The dbname is the database name that is used by SQL Server to access the database. Theskipchecks parameter is optional and instructs the server to either update the statistics forthe database or not.

    For example, if we wanted to detach the Northwind database that comes with SQL Serverthe following statement would accomplish that feat:

    sp_detach_db 'Northwind

    Once the database is detached you can start moving the database to another location ortransport it to the location where it is needed and can be attached to the server in order to

    access the database once again in SQL Server.

    To access the database once again via the database management system, it must bereattached to the database.

    In order to perform the attachment of a database via Enterprise Manager, right click on thedatabases tab in Enterprise Manager, select the All Tasks option and then the AttachDatabase option from the menu.

    The following illustration shows the options needed to perform the operation:

  • 8/6/2019 SQL 2000 Tutorial

    13/65

    By selecting the Attach Database command the following dialog box is shown to continuethe operation.

    The first parameter that must be input is the mdf file for the database that needs to beattached. The command button shown to the left will bring up the file browser to allowthe standard file selection methods to be employed.

    After the file is selected, it can be verified using the Verify command button. A name isgiven to attach the database as and also to specify the owner of the database.

    The OK command button will finalize the attach operation and shows the following dialogbox to alert the user that the operation was successful.

    Clicking the cancel button can be used to cancel the operation from continuing.

    The database can also be attached by opening up a Query Analyzer session and usingTransact-SQL to perform the operation. The syntax of the attach command is as follows:

    sp_attach_db 'dbname' ,'filename_n'

    The dbname is the database name that is used by SQL Server to access the database. Thefilename_n indicates that there can be more than one file associated with the database.

  • 8/6/2019 SQL 2000 Tutorial

    14/65

    There can be filename1 through filename16 files associated with the database. Once it isattached the database can be accessed by SQL Server again.

    For example, in order to attach the Northwind database we detached in the previousexample, the following statement can be used:

    sp_attach_db 'Northwind' ,'c:\\\\\\\\\\\\\\\\somelocation\\\\\\\\\\\\\\\\northwind.mdf',c:\\\\\\\\\\\\\\\\location\\\\\\\\\\\\\\\\northwind.log

    Many people may be asking themselves why they may need this ability, but for those of uswho have had to send a database somewhere else for it to be used, it is a blessing that itexists.

    I hope that moving the database from one location to another seems like a doable task afterreading this.

    Import and export in SQL Server

    SQL Server: The Advantage of the Import and Export in SQL Server Tools

    While SQL Server can be used to house the data that your company maintains on a dailybasis and offers a way to effectively and efficiently manage the objects and data within that

    database, there are often times when getting initial data into a database can be a hassle.

    However, not only does SQL Server manage the data and objects contained within thedatabase, it has tools that can be used to get data into tables quickly from a variety ofexternal sources.

    SQL Server provides to those who use it, the ability to import and export in SQL Server tomany different formats. This can be extremely useful for someone wanting to quickly getdata into the database or out of the database for any reason.

    For example, an agency that sells mailing lists could easily export the data from a SQLServer database to a format that could be burned onto a CD and delivered to the customervery quickly.

    On the other hand, the same company could buy a mailing list file from another agency orthird party and import the data into their database and save the time of having to key thedata into the database or an application.

    So how can the import and export in SQL Server data tools that are provided by SQLServer be used to get data into a database quickly?

  • 8/6/2019 SQL 2000 Tutorial

    15/65

    In order to use the import and export in SQL Server Data functions, right click on the serverin Enterprise Manager that you would like to use as a basis for the Import or Export.

    Then select the Import Data or Export Data menu option from the All Tasks selection asshown in the image below:

    The interface for Import Data and Export Data is the same, each presents the user withdifferent options for the destination and source for the data involved in the operation.

    Regardless of what operation you wish to conduct when transferring the data, an import oran export, each option will provide you with the functionality you need.

    For clarification, regardless of whether you want to import or export data, the options areprovided that will allow an import or an export to occur once the operation is initiated. Oncethe selection is made, the following window appears:

  • 8/6/2019 SQL 2000 Tutorial

    16/65

    Select the Next button to continue with the Import/Export Wizard. This will bring up thefollowing screen:

  • 8/6/2019 SQL 2000 Tutorial

    17/65

    This screen will allow the user to select the data source, which is a drop down list of all thetypes of data that can be used with the import/export.

    These include many different formats, not just SQL Server data. The source type can beSQL Server, Access, Oracle or any other data store that can be accessed via ODBC aswell. After the data source type is selected, the user is then presented with thespecifications needed to specify the location of the source data.

    Each option comes with different parameters needed to locate, connect and open the datasource. Once the data source is configured, click next which will allow the selection of thedestination for the data.

    In most instances you will be required to input information that will allow the database toverify who you are and securely control access to that particular repository of data. Eachtype of data has differing parameters and must be experimented with in order to learn thefull functionality of the import/export capabilities of SQL Server and the tools it offers. Thefollowing graphic illustrates this screen:

    This screen is used the same way as the previous one used to input the source of theinformation for the import and export in SQL Server.

    It functions the exact same way the source screen works except that it represents theconnection used to access the destination database. If the user wants to go back to thesource screen, click the back button. Clicking next will bring up the next screen.

  • 8/6/2019 SQL 2000 Tutorial

    18/65

    This will allow the user to select the type of objects that they want to move.

    The user can select to move tables, use a query to specify the data or move data andobjects between databases.

    Selecting the copy tables option will allow the user to select tables to move in their entiretyto the destination. The use of the query option will allow the user to enter a query to specifythe data that needs be moved. This can be used to limit the fields or the amount of databeing moved.

    The transfer objects option will allow the selection of objects to be moved between SQLServer databases.

    All of these options are very important when trying to determine how to import and exportdata in SQL Server. After the choice is made, the user can click next to move on to the nextscreen, which is shown below.

  • 8/6/2019 SQL 2000 Tutorial

    19/65

    To continue with the import and export in SQL Server operation, this screen will allow theselection of the source and destination objects and the data transformations that need tooccur in order to move the data to the correct location.

    These transformations can be a straight copy or they can be the result of data manipulation

    via scripts in order to make the data fit the format you need or transform the data into otherelements. Once this is complete, click the Next button, which will bring up the followingscreen.

    After this information is input, our import/export operation is almost ready to run on theserver to complete the movement of the data.

  • 8/6/2019 SQL 2000 Tutorial

    20/65

    This will allow the user to run the import/export now or save the configured import/export asa DTS package to be run later or saved on the server to be run as needed.

    You may be asking yourself why this utility to import and export in SQL Server is soadvantageous, imagine if you had to use data entry tasks in order to manually enter a list ofthousands of records of data.

    How much time could be saved if the data could be loaded via a file in the import/exportdata utility?

    Experience has proven to me that this tool can prove to be invaluable if the developer ordatabase administrator becomes familiar with the power that it provides. It has saved menumerous hours on projects and has been used exclusively for data transformation tasksthat would not have been possible without a tool such as this.

    Moving data using the import and export in SQL Server can prove very useful along with therest of the DTS features in SQL Server.

  • 8/6/2019 SQL 2000 Tutorial

    21/65

    SQL Server indexes - Boosting performance in the

    database

    SQL Server indexes:

    A couple of years ago your IT department made the investment to purchase SQL Server inorder to manage and maintain your data and information.

    This was an investment in our future and the future of our organization. We had evaluatedthe database options available to us, and decided to go with SQL Server.

    After a while, we were wondering why the database that promised such robust performancefor our dollar was not working properly and was taking way too long to return the recordsthat we needed from it.

    Every operation you do involving the databases that you have seem to take longer andlonger with each passing day.

    You know all of the data is there and you need to access it, however, with the delays youexperience you become frustrated and give up.

    Why not evaluate the normalization of your database design, gather statistics on yourdatabases and have a look at what indexes are present on your databases and what SQLServer indexes may need to be added in order to get the performance that you require anddeserve?

    SQL Server indexes are used for many reasons.Some of those reasons are listed below:

    To ensure data integrity

    To ensure data accuracy

    To speed up data storage and retrieval

    To help the database engine manage the data that it is responsible for

    Indexes are a good practice to use when working with databases because they candefinitely have an impact on the performance of some operations that take place in thedatabase.

    For example, I have seen a query take over twenty-five minutes until proper indexes wereadded to the table based on usage and needs.

    After the indexes were added the same query took under 10 seconds to run and return thedata from the database.

  • 8/6/2019 SQL 2000 Tutorial

    22/65

    While indexes are a good thing to utilize in a database architecture and design, they can beoverdone just like any good thing.

    Each index added will require some additional resources to be used by the server when anoperation involving the table or tables in question takes place.

    Therefore, the more indexes you add to a table, the more checks and balances thedatabase engine has to maintain before the operation can be completed and the resultsreturned to the user.

    How many indexes are enough? That is up to the designer and relies on the situation athand. If a table already has a couple of indexes associated with it and another needs to beadded, the index may or may not make performance any better.

    Adding more indexes to a table can increase performance and reduce the time it takes toperform an operation, however, they should be used with discretion.

    SQL Server allows the user to view statistics and the performance plan associated withstatements that are going to be executed against the database. These aids can helpdiagnose problems that may be helped with the addition of new indexes or the subtractionof existing ones.

    After the decision has been made to work with the SQL Server indexes used with aparticular table in a database, Enterprise Manager can be used to manage the indexes ofthat table.

    In order to work with the indexes assigned to a table, expand the database that contains thetable you want to work with, expand the tables in that database and right click on the table

    in question.

    Select the All Tasks menu option, which will bring up the submenu options desired. Thefollowing illustration shows the menu options described above.

  • 8/6/2019 SQL 2000 Tutorial

    23/65

    After these menu options become available, select the Manage Indexes menu option inorder to work with the indexes associated with that table. The index management is

    accomplished using the following interface:

  • 8/6/2019 SQL 2000 Tutorial

    24/65

    The first option shows the database that you are currently working with and can be changedfrom within the interface to switch to another database. The next option shown is theselection of the table that you want to manage the indexes for. The lower half of the screenshows the existing SQL Server indexes that the table selected has.

    There are also command buttons on the bottom portion of the screen that allow you add anindex, edit an existing index or delete an existing index. In order to add a new index, clickthe New button and the following dialog will be presented to the user.

  • 8/6/2019 SQL 2000 Tutorial

    25/65

    The first step that is needed when creating a new SQL Server index is to assign the index aunique name within the database so that it can be distinguished from other indexes.

    The next portion of the index creation screen is a table that allows the selection of the fieldsthat make up the index.

    There can be more than one field used to make up an index. For example, if you were tohave fields called firstname, middlename and lastname, they could be indexed as one fieldto allow the searching for the full name to perform better on the server.

    The order of the columns in the index can be sorted based on how the index needs to bearranged within the database with the Up and Down command buttons on the screen.

    After the fields that make up an index are selected, the options associated with that indexmust be selected in order to help describe the way that index will function within thedatabase management system.

    Some of these options can be set whether or not the index will contain unique values,whether the index will ignore duplicate values or whether or not the statistics will berecomputed based on the index.

  • 8/6/2019 SQL 2000 Tutorial

    26/65

    Unique values dictate whether or not the index can contain duplicate values.

    Ignoring duplicate values will instruct the database engine to allow duplicate values in theSQL Server indexes selected.

    A very important option is the computation of statistics. Statistics allow the database tocompile information about the SQL Server indexes and data in the database to speed upperformance when the database is used. Once the index is complete, click the OK button tosave the changes.

    SQL Server jobs

    SQL Server jobs:

    In the day-to-day operations of running a business, employees can get caught up in morethan one project, as is often the case.

    We may be IT professionals but there is a limit to the amount of work that we can handle inone day and still stay on track.

    With the amount of multitasking that employers feel their employees should be able tohandle increasing with each passing day, the need to find a way to help themselves get the

    job done becomes increasingly more important.

    Finding help and ways to get solutions into production even faster can make the day less

    stressful thereby making it more productive in the long run.

    In the daily routine of a database administrator or a database developer, SQL Server hassome functionality that can make life simpler and more dependable in the long run: SQLServer jobs.

    How can the ability to create a job to handle routine tasks make the life of a databaseadministrator or developer and how are SQL Server jobs created?

    A SQL Server job is a collection of steps executed by the database engine by SQL ServerAgent.

    The job can perform many different functions within it that can save time and effort on thepart of employees.

    For example, a job can be created to import a daily update file internally or externally via anFTP server.

    Another job can be configured to handle routine maintenance tasks as well as handling one-time production updates that may be needed in the future.

  • 8/6/2019 SQL 2000 Tutorial

    27/65

    A job has many different options that can be configured during its creation in order toperform the duties that is needed of it.

    In order to manage the jobs within a SQL Server database, use Enterprise Manager, andexpand the Management node in Enterprise Manager.

    Under the Management node is a node entitled SQL Server Agent. Expand this node andyou will see the Jobs item that is used to represent the jobs within the system.

    To see the jobs currently in the system, select Jobs. See the following illustration for anexample of the steps described above:

    The window on the left will show the jobs currently in the system. This window displays a lot

    of information about the SQL Server jobs currently in the system that can prove valuable.

    The first column lists the name of the job that was entered when it was created.

    The second column lists the category of the job that was assigned at the time of the job'screation. This helps to clarify the jobs and organize the jobs in the system.

    The next column tells whether or not the job is enabled in the system.

    If you wish to disable or enable a job in SQL Server, right click on the job and select on theDisable Job or Enable Job option from the popup menu.

    The next column tells whether or not the job is runnable in the system.

    After that there is a column, which tells whether or not the job is scheduled to run in thesystem.

    The status column alerts the user to what is currently going on with the job. If the job isrunning it alerts the user to what step it is in currently.

  • 8/6/2019 SQL 2000 Tutorial

    28/65

    The last run status column tells the status of the jobs last run and when that occurrencetook place.

    The final column shown tells when the next scheduled run is to take place.

    To see the properties of a job in the window, right click on the job and select Properties fromthe popup menu or double click on the job. Either of these actions will bring up the followingscreen in order to set and/or view options contained in that job.

    The first tab (General) of this dialog shows the name of the job, when the job was created,whether or not the job is enabled, the category the job falls into, who owns the job within thedatabase and a description of the job.

    To disable a SQL Server job, uncheck the Enabled checkbox and the job will no longer runin the database if it was scheduled to do so.

    The Steps tab of this dialog brings up the following screen:

  • 8/6/2019 SQL 2000 Tutorial

    29/65

    Each step within the job will be identified within this screen.

    These steps can include executing data transformation packages, executing queries,executing stored procedures, etc.

    Within this interface you can move the order of the steps around so that they occur in aspecific order, as well as, add new steps or edit existing steps.

    If you select a step and select the Edit button, the following screen appears:

  • 8/6/2019 SQL 2000 Tutorial

    30/65

    This screen is used to set the command that is to be executed during the current step.

    You can also specify the name of the step, the type of command to execute and the exitcode of the process if successful.

    The tab also has a Schedule tab that can be used to manage the schedule of the SQLServer jobs.

    This will allow the job to be set to occur once a daily, multiple times per day, weekly,monthly or just a one time. The job can be set to run at a certain times per day on arecurring basis as well, such as every hour or at a certain time per day.

    The following screen shows the scheduling tab:

  • 8/6/2019 SQL 2000 Tutorial

    31/65

    To work with the schedule, click the New Schedule or the Edit button.

    The New Schedule button will allow a new schedule to be input for the job.

    The Edit button will allow the edit of the current schedule.

    There is also a Notifications tab that can be used to handle notifications from the SQLServer in the event that something unusual occurs with the job while it is running.

    The following screen shows the notification dialog which allows the selection of notificationsoptions:

  • 8/6/2019 SQL 2000 Tutorial

    32/65

    Notifications can be sent in multiple methods. For the notification to work, there must beoperators set up within SQL Server to receive them.

    The notification can be an email, a page or a net send. Each notification can be used toalert the operator that something has occurred on the server and the actions are controlledby SQL Server Agent.

    Once the SQL Server job is configured, the changes can be saved and the job can now beused to perform routine tasks on a regular basis which can free up resources within yourorganization.

    Creating a SQL Server Maintenance Plan

    SQL Server Maintenance Plan:

    SQL Server is a very capable database in terms of storage capacity and performance.

    It can be used successfully to manage large stores of data and provide a database

    management system for anyone who needs it and can work with it properly.

    In order to properly manage the database and keep the database performing at an optimallevel, routine tasks must be taken care of on the database.

    These routine tasks include SQL Server maintenance jobs that will not only keep the dataand the engine performing at satisfactory levels, but will also keep the data backed up inorder to aid in the occurrence of a disaster.

  • 8/6/2019 SQL 2000 Tutorial

    33/65

    The only way to be ready for a disaster is to plan ahead and ensure that the SQL Servermaintenance plan a nd disaster recovery measures you have in place will work.

    A good SQL Server maintenance plan can do wonders if planned correctly, implementedsuccessfully and managed appropriately and properly.

    SQL Server provides a maintenance plan that help to implement appropriate measures toensure that your database is safe and properly maintained.

    So what is a database maintenance plan and how can you configure a good SQL Servermaintenance plan?

    A maintenance plan is a set of measures taken to ensure that a database is properlymaintained and that routine backups are scheduled and handled.

    Within SQL Server, a database maintenance plan can include tasks such as backups of thedatabase, backups of the transaction log, recomputing statistics on the database, managing

    indexes and taking care of internal data storage issues.

    A nice feature of SQL Server is that the maintenance plan can be configured by a wizard,which can help alleviate some of the burden of creating the plan. It can also ensure that thecommon features of the maintenance plan are taken care of.

    The Database Maintenance Plan Wizard relies on a graphical user interface to give the userthe ability to visually create and implement one or more jobs within SQL Server that will rununder SQL Server Agent.

    These jobs can automatically check the database integrity, get rid of unused space within

    the database, which will increase performance, reorganize your indexes, create thebackups of the database and transaction logs.

    For most administrators and instances, the wizard will suffice in creating the backup planunless you want to create a custom maintenance plan yourself.

    In order to use the wizard to create the maintenance plan in Enterprise Manager, select theTools menu option and navigate to the Database Maintenance Planner option. This willbring up the following screen:

  • 8/6/2019 SQL 2000 Tutorial

    34/65

  • 8/6/2019 SQL 2000 Tutorial

    35/65

    This screen allows you to specify the database(s) that will be involved with the maintenance

    plan that you are creating. The available options are

    All databases

    All system databases (master, model, and msdb)

    All user databases (all other than master, model, and msdb)

    These databases which allows a selection from a list of one or more databases toinclude

    Depending on which databases you would like to include in the SQL Server maintenance

    plan, make the selection from this screen and continue with the wizard.

    Clicking the Next button will allow you to continue with the creation of the databasemaintenance plan. The Next button will open the following screen:

  • 8/6/2019 SQL 2000 Tutorial

    36/65

    The first option in this dialog will instruct the plan to reorganize the data and index pages inthe database.

    If this option is selected, the statistics are recreated automatically when this step runs.

    Updating the statistics will increase the performance and reliability of the database(s) inquestion. If you select the option to reorganize then you cannot select the update statisticsbox because the statistics will automatically get recreated.

    You can however, just select the update statistics box without the reorganization. You canalso specify that you would like to remove unused space from the database files.

    During the course of normal operations, database files will become filled with unused space,which will lead to decreased performance.

    After these options are selected, click the Next button to continue with the wizard and thefollowing screen is shown:

  • 8/6/2019 SQL 2000 Tutorial

    37/65

    This screen allows you to check the integrity of the database.

    The integrity check can be configured to include indexes and attempt to repair any problemsthat it finds.

    The checks can also be setup to be performed before doing a backup. This option can havenegative side effects either way.

    The integrity check may take up precious time on the server, but it can fix problems. On theother hand, the check may not be able to fix all the problems that it encounters. The checkcan also be scheduled by clicking the Change button to set up the schedule.

    Selecting the Next button will bring up the following screen:

  • 8/6/2019 SQL 2000 Tutorial

    38/65

    This screen allows the creation and schedule of the backup and to specify the location ofthe backup file, as well as, to verify the integrity of the backup when the operation iscomplete.

    If you select the disk option on this screen you will be taken to the screen to configure thefile location and select options to remove older backup files that may be in that locationalready.

    This screen is shown in the following illustration:

  • 8/6/2019 SQL 2000 Tutorial

    39/65

    Clicking Next will allow you to specify information relating to the transaction log backup asshown in the following image:

  • 8/6/2019 SQL 2000 Tutorial

    40/65

    This screen functions the same way as the screen for configuring the database backup. Itallows the selection of the file location, the verification of the integrity and the scheduling ofthe backup.

    After clicking Next, if disk was selected as the location of the backup file, the user will bepresented with the following screen:

  • 8/6/2019 SQL 2000 Tutorial

    41/65

    This screen allows the selection of the directory location for the backup file, as well as the

    ability to instruct SQL Server to create a subdirectory for each database being backed upwhile the operation is running.

    You can also specify the removal of old backup files and assign an extension to the backupfiles. Clicking on the Next button will bring up the following screen:

  • 8/6/2019 SQL 2000 Tutorial

    42/65

    This allows you to specify whether or not to generate a report for the SQL Servermaintenance plan and store that in a specific location.

    You may also delete report files older than a specified timeframe. Operator emailnotifications can also be configured on this page as well.

    Selecting Next will bring up the following screen for input:

  • 8/6/2019 SQL 2000 Tutorial

    43/65

    This screen deals with options relating to whether or not the SQL Server maintenance planhistory will be stored in a SQL Server database somewhere for easy retrieval and historicalpurposes.

    Selecting Next will finalize the maintenance plan and bring up the confirmation screen asseen in the following illustration:

  • 8/6/2019 SQL 2000 Tutorial

    44/65

    This will allow the naming of the SQL Server maintenance plan and clicking finish willgenerate the necessary jobs that are needed to perform the database plan.

    The objects generated by these steps can be seen by looking at the SQL Servermaintenance plan for the database or looking at the individual jobs created and scheduledon the server.

    SQL Server Backup

    SQL Server Backup:

    When using SQL Server to maintain and manage a database, the integrity, accuracy andavailability of that data if often critical to the success of a business.

    If data becomes unavailable or the database becomes inaccessible to the users of asystem, a business can be in a lot of trouble.

  • 8/6/2019 SQL 2000 Tutorial

    45/65

    SQL Server has the ability to make backups of databases so that the data can be restoredin case something tragic happens to the database. A SQL Server backup will play a criticalpart to any disaster recovery plan in case an emergency does occur.

    They are crucial to the success of any information technology department. How do youperform a SQL Server backup in order to ensure that the database will be available in theevent that something does happen sometime down the road and your database must berestored from a backup device?

    In order to backup a SQL Server database using Enterprise Manager, right click on thedatabase that you want to back up. The following illustration shows the menu optionsneeded to navigate to the necessary option.

    After the appropriate menu is available, from the All Tasks menu item select the BackupDatabase submenu item. This will initiate the SQL Server Backup Database operation sothat the parameters needed to perform the backup can be entered into the database.

    This will bring up the following screen to begin the entry of the information needed toperform the backup of the database:

  • 8/6/2019 SQL 2000 Tutorial

    46/65

    The first option in the screen is to specify the database that is to be backed up and thename of the backup as well as a description of the backup.

    A name and description are necessary in order to help identify saved SQL Server backupplans in the database. After this information is entered into the window, the backup type

    must be selected in order to specify what type of backup is to be performed.

    There are four backup operations that can occur within the database. This can be acomplete database backup, a differential database backup, a transaction log or file/filegroupbackup.

  • 8/6/2019 SQL 2000 Tutorial

    47/65

    A complete database backup will back the entire database structure up to the devicespecified. It is a complete copy of the database selected and will include everything in thedatabase including the data and the objects.

    A differential backup is another option. It deals with only backing up the database and itschanges since the last full database backup was performed. A transaction log backup willbackup the current transaction log so it can be restored at a later date.

    The transaction log is a log of the transactions that have taken place in the database. A fileor filegroup backup deals with making a SQL Server backup of a specific part of the files orfilegroups involved with the make up of the database.

    Once the desired backup type is entered, a destination for the database backup must beinput into the equation. This will inform the database where the backup is to be saved. Thebackup can be saved to a disk or to a tape backup device.

    To enter a backup device to save the backup to, click the Add button to open a dialog that

    will allow for the selection of the backup location and the device to hold the backup.

    After finalizing the selection of the backup destination, the choice must be made whether toappend to the existing media or overwrite the existing media with the result of the backup.

    Once all of these options have been entered, the database backup can be scheduled inorder to make this a process that occurs on a regular basis. Scheduling a backup procedurein SQL Server puts the workload on the server to execute the backup on routine basis anddoes not force a database administrator to perform the backups.

    The only job that someone has concerning the SQL Server backups are to either routinely

    check them for success or configure the server to send alerts to users when specific actionsoccur on the server.

    To schedule the backup of the database, select the checkbox and then click the commandbutton to bring up the scheduling dialog window. The following screen shows this operation:

  • 8/6/2019 SQL 2000 Tutorial

    48/65

    The options on this screen deal with the timing of the SQL Server backup and theconditions that need to be met before the server is to run the database backup.

    The schedule can be given a name to help distinguish it within the database. It can also beenabled or disabled using the Enabled checkbox option. There are four different schedulingoptions that can be used within the system to determine when to run a job within SQLServer.

    These four options are to start when agent starts, start when the CPU is idle, a one time orto create a recurring job.

    The first option will start the job whenever SQL Server Agent starts. SQL Server Agent is aservice that runs specific tasks within the database management system.

    The second option is to start the job when the CPU becomes idle.

    The third option is to create a job that occurs once at a specific date and time.

    The final option is to create a SQL Server backup job that occurs on a routine basis that canbe scheduled to occur as often and whenever it is necessary.

    The following screen shows the job scheduling options available to handling recurring jobs:

  • 8/6/2019 SQL 2000 Tutorial

    49/65

    Once the job schedule is created, clicking OK will accept the changes and create a job

    within the database.

    This job is responsible for the backup and is run by SQL Server Agent whenever thescheduled time occurs. When the scheduled time occurs on the server, SQL Server Agenttakes over and runs the job and the steps associated with it. While running the job, thestatus of the SQL Server backup is updated to alert the user of the database what isoccurring with the job. Each step and operation is logged in the database and updated inthe job history tables stored in the database.

    SQL Server Restore DatabaseSQL Server Backup: SQL Server Restore Database:

    The database jobs are working efficiently and your data is now being backed up on aroutine basis so that in case something happens you have a way to restore your database.

  • 8/6/2019 SQL 2000 Tutorial

    50/65

    Then one day it finally happens, your server crashes and your mission-critical database isnow corrupt and cannot be accessed by SQL Server's engine.

    Now comes the time to put the database backups to use that you have created in order toget your database working again.

    A database can be restored in SQL Server using either Enterprise Manager or with QueryAnalyzer. Most people are more comfortable using Enterprise Manager and its windows-likegraphical user interface to accomplish the database restoration.

    However, some people prefer to use Query Analyzer and the Transact-SQL language toaccomplish the SQL Server database restore.

    The graphical user interface of Enterprise Manager makes the job of restoring a databaseeasier for those who do not know Transact-SQL and do not want to take the time to learn it.

    To restore a database from backup using Query Analyzer, open a session of Query

    Analyzer and enter the restore command. The syntax for the most basic command torestore a database is as follows:

    RESTORE DATABASE databasename FROM backupdevice

    The databasename parameter is the name of the database that is to be restored. Thebackupdevice parameter is the name of the backup device to use for the source of thebackup.

    For example, the following command will restore the Northwind database from the backupdevice Nwind1.

    RESTORE DATABASE Northwind FROM Nwind1

    This gives a brief description of how to perform a SQL Server restore database fromdatabase backup using Query Analyzer and the Transact-SQL commands to perform theoperation.

    While some people prefer this method, most people prefer to use Enterprise Manager inorder to handle a restoration of a database backup.

    To restore a database from a backup set using Enterprise Manager, right click on thedatabase that you want to restore and select the All Tasks menu item in order to get to theRestore Database option item.

    The following illustration shows the menu options needed in order to execute the SQLServer Restore Database option:

  • 8/6/2019 SQL 2000 Tutorial

    51/65

    This option initiates the request to perform the database restoration process.

    In essence, this wizard is creating the same Transact-SQL statements that can be used

    Query Analyzer to perform the restore operation on the database in question. The restoredatabase wizard screens will submit this statement to the SQL Server engine to perform theoperation.

    After selecting the restore database menu option, the following screen appears:

  • 8/6/2019 SQL 2000 Tutorial

    52/65

    The first parameter that should be entered is the name of the database that is to berestored. If the database exists already, the database will be overwritten by what iscontained in the backup set.

    The next option that needs to be entered is the selection of the backup type that is to berestored. The type of restore option used is determined by the type of backup set that youare performing the restoration from.

    The possible options are database, filegroups or files or from device. The user can also usethe dropdowns on the screen to show the backups that have taken place for the database inquestion. This can be helpful if the user is unsure of which backup to do the restoreoperation from.

    There is also a dropdown that allows the user to select which backup set to restore first. Insome cases restoring a database can require more than one backup set to get the database

  • 8/6/2019 SQL 2000 Tutorial

    53/65

    completely restored to the state that is needed for proper operation while minimizing theloss of data.

    The key factor that needs to be considered when a backup strategy is being devised andimplemented is the amount of data and time that can be afforded to be lost in the case of adisaster.

    For this reason, many companies decide to create different types of backups throughout theday and week in order to ensure that the least amount of data and effort is wasted if adisaster occurs.

    In the SQL Server restore database wizard there is also an Options tab that helps to furtherdefine the restoration operation that needs to be performed. The Options tab is shown in thefollowing image:

  • 8/6/2019 SQL 2000 Tutorial

    54/65

    This window will allow the user to further specify options that are to be used during theprocessing of the SQL Server restore database operation.

    The user can specify whether or not to eject each tape during each step of the restorationprocess if tapes are being used for the restore operation.

    There is also an option to prompt for confirmation before restoring each backup that is beingused. The option may also be checked to overwrite an existing database with media used inthe process of restoring the database.

    After these options are specified, there are choices that can be selected by the user tospecify how to leave the database after the recovery operation has been completed.

    The first option is to leave the database operational. This selection restores the databaseand makes it operational for use, however, it also places a restriction on the database sothat no additional transaction logs can be restored.

    The second option is to leave the database nonoperational after the SQL Server restoredatabase operation but allow the user to restore more transaction logs which can helprecover even more data and make the database even more current with what was lost.

    The final option is to leave the database in read-only mode and allow the restoration ofadditional transaction logs.

    Once the options are selected, click OK and the restoration of the database will proceedwith the options that have specified and will alert the user when the operation is complete orfails.

    SQL Server Profiler - Analyzing the database

    What is Microsoft SQL Server and what is SQL Server Profiler? What does it have to offer?

    Microsoft SQL Server is a powerful database management system, as many of us know.Those of us who have worked with SQL Server know that this product, as many otherproducts of this type, make our lives as information technology professionals so mucheasier than it would be without it.

    Without the power it offers us, how would we manage to do the work that it performs in thebackground in as much time? However, in order to tap into the power of SQL Server, theinteraction with the database must be done correctly and the objects residing in thedatabase must be correct as well.

    Any component used by an application on the server must be correct and accessedcorrectly. What happens when the tools we are using to access the database and

  • 8/6/2019 SQL 2000 Tutorial

    55/65

    something in the database are not exactly working as we expected? How do we go aboutdetermining where the problem is?

    SQL Server Profiler is one tool that can be used to provide a wealth of information that canbe used in order to diagnose a problem or error in our application.

    What is Profiler? Profiler is a utility that runs on the server that monitors and logs specifiedactivities on the server in order to produce a listing of all the activity occurring on the server.

    SQL Server Profiler is configured by the user to capture the events that they want tomonitor. This allows the user to create a customizable view each time that they have anissue they want to watch.

    This is done by the use of a trace running on the server that is configured to capture thedata deemed necessary by the developer or administrator in order to determine where theproblem may be.

    To run Profiler from Enterprise Manager, select the SQL Server Profiler option from theTools menu as shown in the image below:

    Once the SQL Server Profiler option is selected, the following screen will open for the userto interact with the utility and configure the trace that may be needed at the time.

    This screen has many options available that can be used to configure the trace running onthe server.

    This article will focus on setting up a trace in order to diagnose a problem on the server orto monitor an event that might be returning questionable results.

  • 8/6/2019 SQL 2000 Tutorial

    56/65

    In order to configure a new trace select File | New | Trace from the menu options availableon the screen. See the following image for an illustration of the menu options needed toopen a new trace.

    Once this option is selected, the interface will open a screen that will allow the user toconnect to the server in question.

    Once successfully connected to the server, it is time to configure the trace that will run onthe server. The configuration screen is shown in the following graphic:

  • 8/6/2019 SQL 2000 Tutorial

    57/65

    The configuration screen consists of four tabs, the General tab is illustrated above.

    This tab is used to give the trace a name and select the SQL Server that the trace will runagainst. If a trace template exists that has already been configured, it can be selected in theUse the following trace template section.

    The option exists to save the trace results to file or to a table. Either of these options willinstruct the server where to save the results of the trace so they can be retrieved later.

    Each option allows the user to regulate the amount of rows that Profiler will capture duringthe trace. If the user would like the trace to stop automatically, a date and time can beselected for the server to stop the trace automatically.

    This can be advantageous if you have many windows open and do not want a lot of activitylogged from a very busy server by not letting the trace run for a long time.

    The next tab is the Events tab. This tab is shown below:

  • 8/6/2019 SQL 2000 Tutorial

    58/65

    This tab allows the addition or removal of events that occur on the server that are to betraced by the server.

    There are numerous events available that can be used depending on the informationneeding to be traced by the user. Each of these events will be logged by SQL ServerProfiler as a different type of event so that the results can be searched easily by the type ofevent that occurred.

    The next tab is the Data Columns tab. This tab is shown in the following graphic:

  • 8/6/2019 SQL 2000 Tutorial

    59/65

    This tab is used to instruct the server which data to capture in SQL Server Profiler.

    Some common elements are ApplicationName, which is the name of the application thatcalled the event, the TextData, which is the instruction as seen by the server, theDatabaseName, which is the name of the database being accessed by the statement andDuration, which is the length of time needed to process the statement. This field can beparticularly useful in diagnosing a long running statement in a stored procedure.

    The final tab is the Filters tab. This tab is shown in the following graphic:

  • 8/6/2019 SQL 2000 Tutorial

    60/65

    This tab will allow the user to configure any filters that they would like to apply to the trace inSQL Server Profiler.

    This can restrict the amount of data going into the trace. For example, if a particulardatabase is needed, set the DatabaseName field to the desired database name.

    Once all of the options are configured, click the Run button in order to run the trace. Thetrace screen is shown in the following image:

  • 8/6/2019 SQL 2000 Tutorial

    61/65

    To stop the trace, select the red square button on the toolbar.

    If the results were saved to a table, the table can be accessed just like any other table inSQL Server.

    By analyzing the results of the trace, the user can see what activity is taking on the serverand in what order when they are making calls to the database, which can be a powerfulwhen trying to debug a problem that may be occurring or returning unexpected results.

    The Purpose of the SQL Server Transaction Log

    SQL Server Transaction Log:

    While working with SQL Server, there can be huge amounts of data in the database that isstored in the underlying files.

    SQL Server stores its data in files that are maintained by the database engine. These filesrely on the underlying hardware and networking architecture in order to function correctly.Without the power it offers us, how would we manage to do the work that it performs in thebackground in as much time?

  • 8/6/2019 SQL 2000 Tutorial

    62/65

  • 8/6/2019 SQL 2000 Tutorial

    63/65

    The options allow you to specify the location of the SQL Server transaction log files that areused by the database that you are creating. These transaction log files are stored just likethe data files used in SQL Server.

    These files can also be configured just like the data files in SQL Server. The screen aboveshows the options available.

    For example, along with the file location you can specify a minimum size to start the SQLServer transaction log file out with. This size is just the minimum starting point because asthe database is used the transaction log will grow.

    The growth must be planned for and the options must be configured to handle the growthaccordingly or error messages can occur relating to the transaction log being full.

  • 8/6/2019 SQL 2000 Tutorial

    64/65

    The rate at which the transaction log files grow can be specified by a size in megabytes orby a percentage. This setting tells SQL Server that when the transaction log reaches aspecified point, automatically grow the file by the amount of growth specified in order toaccommodate future transactions.

    The other option that can be set is the maximum size of the transaction log files. They canbe set to have unrestricted file growth or they can be set to only occupy a specific amount ofspace in megabytes.

    One thing to keep in mind is that the transaction logs can be used in a backup situation sopossibly putting them on a disk other than that occupied by the primary data files may be agood idea for future use.

    To elaborate on the idea of using the SQL Server transaction log as part of the backup andstoring it on a separate drive, the transaction log can be backed up and used to recovertransactions since your last backup.

    The last entries you have made will be stored in the transaction log and can be reenactedon the database to give a better database restoration by minimizing the amount of work lostsince the last backup.

    So what exactly occurs during the logging of a transaction? When a transaction is logged inthe database it can occur in different manners based on the statement that is being logged.

    In essence, however, all transactions log a copy of the old data and the new data in thetransaction log. Some transactions will log of copy of the entire row and other transactionswill log the bytes that have changed during the transaction.

    On many occasions it is not necessary to know exactly what is occurring in the transactionlog as long as it is utilizing correctly when programming with it.

    How can the SQL Server transaction log be used when developing stored procedures,database objects or interactions with the database in order to ensure that proper recoverymethods can be implemented during the development of these objects or segments ofcode?

    When using Transact-SQL to interact with the database engine to process the statementsneeded, effective use of certain statements within the code will allow for transactions andrecovery options to be implemented in case something occurs in the code we create.

    These statements are the Begin Tran, Rollback Tran, Commit Tran and the Save Tran.

    The Begin Tran statement will instruct the database engine to being a transaction blockwithin the database so that the work can be handled explicitly in the code.

    For example, if you wanted to insert a group of records into a specified table only if a certaincondition was true, you could begin the transaction, insert the records and check thecondition to see if it was met.

  • 8/6/2019 SQL 2000 Tutorial

    65/65

    If the condition was met you could then issue the Commit Tran command to commit theblock of transactions since the last Save Tran orBegin Tran was encountered.

    If the condition was not met you could, on the other hand, issue the Rollback Tran in orderto stop the transaction and rollback all changes to the database since the last Save Tran orBegin Tran was issued.

    The Save Tran command is issued to save a point in the transaction handling that will allowa save point to be specified. For example, you could create a save point during a largeoperation every so often so that the rollback or commit trans is not having to handle asmany records when it is performed.

    One thing to keep in mind with this is that it causes an impact on performance duringexecution of these statements as they are database operations just like statements youexecute.

    We have examined the transaction log and how it may prove valuable to us when working

    with SQL Server and have found some good uses for the transaction log and the ways tointeract with it.