SQL Server 2000 Tutorial
SQL Server 2000 Tutorial
Note that this tutorial was written for those using the 2000 edition of SQL Server (SQL Server 2000). For later versions of SQL Server, check out the SQL Server 2008 tutorial.
This SQL Server 2000 tutorial is for anyone who wishes to learn how to use SQL Server 2000. It assumes a basic understanding of databases and how they work.
If you don't currently have an understanding of how databases work, start with the basic database tutorial first. That tutorial covers the basic concepts of databases, so the examples in this tutorial will make more sense once you return here.
To get the most out of this tutorial, you should have a copy of SQL Server installed on your computer (preferably SQL Server 2000), so that you can go through the examples yourself. If you don't have a copy, that's OK - you should still be able to gain an understanding of what SQL Server is and what's involved in using it.
Table of Contents
This tutorial consists of the following lessons:
1. About SQL Server 2. SQL Server - Enterprise Manager 3. SQL Server - Create a Database 4. SQL Server - Create a Table 5. SQL Server - Adding Data 6. SQL Server - SQL Query Analyzer 7. SQL Server Views 8. SQL Server Stored Procedures 9. SQL Server Security 10. SQL Server - Create a Login 11. SQL Server - DTS 12. SQL Server Agent 13. SQL Server Agent Jobs 14. SQL Server - Service Manager 15. SQL Profiler 16. SQL Server - Summary
Microsoft SQL Server is a Relational Database Management System (RDBMS) designed to run on platforms ranging from laptops to large multiprocessor servers. SQL Server is commonly used as the backend system for websites and corporate CRMs and can support thousands of concurrent users.
SQL Server comes with a number of tools to help you with your database administration and programming tasks.
SQL Server is much more robust and scalable than a desktop database management system such as Microsoft Access. Anyone who has ever tried using Access as a backend to a website will probably be familiar with the errors that were generated when too many users tried to access the database!
Although SQL Server can also be run as a desktop database system, it is most commonly used as a server database system.
Server based database systems are designed to run on a central server, so that multiple users can access the same data simultaneously. The users normally access the database through an application.
For example, a website could store all its content in a database. Whenever a visitor views an article, they are retrieving data from the database. As you know, websites aren't normally limited to just one user. So, at any given moment, a website could be serving up hundreds, or even thousands of articles to its website visitors. At the same time, other users could be updating their personal profile in the members' area, or subscribing to a newsletter, or anything else that website users do.
Generally, it's the application that provides the functionality to these visitors. It is the database that stores the data and makes it available. Having said this, SQL Server does include some useful features that can assist the application in providing its functionality.
After looking at the above screenshot, those of you familiar with operating Windows servers will probably notice that Enterprise Manager sits within the Microsoft Management Console (MMC). For those who aren't familiar with MMC, MMC is the standard console for presenting administrative tools (such as the IIS web server) within Windows.
Enterprise Manager enables you to create database objects (such as databases, tables, views etc), you can configure user accounts, you can set up scheduled tasks, transfer data between databases, and more.
You can use Enterprise Manager to connect to as many databases on as many servers as you like. You can group these servers by configuring a "server group". The above screenshot has one server group called "SQL Server Group". This is the default name SQL Server gives to the initial server group. For each server group, you can add any number of servers. And, for each server, you can add any number of databases.
Most of the tasks performed with Enterprise Manager are initiated either from the top menu, or by right-clicking on an icon/object.
Throughout most of this tutorial, we'll be looking at the various things you can do via Enterprise Manager.
If you've only just installed SQL Server, you might notice that some databases have already been created. These are system and sample databases.
Database
Type
Description
master
System database
Stores system level information such as user accounts, configuration settings, and info on all other databases.
model
System database
This database is used as a template for all other databases that are created.
msdb
System database
Used by the SQL Server Agent for configuring alerts and scheduled jobs etc
tempdb
System database
Holds all temporary tables, temporary stored procedures, and any other temporary storage requirements generated by SQL Server.
pubs
Sample database
This database can be used for training purposes, and is based on a book publishing company.
Northwind
Sample database
This database can be used for training purposes, and is based on a fictitious company called "Northwind Traders".
1.
2.
Your new database is based on the "Model" database. The Model database is a system database which is used as a template whenever a new database is created. If you use the left pane to navigate to your database and expand the tree, you will notice that your database already contains a number of objects. For example, it already contains tables, views, and stored procedures. These are system objects which provide information about the database.
Other Options
We have just created a database using the default options. When we created the database, a "Data File" and a "Transaction Log" were created. They were created in the default location for our server.
If we'd wanted to, we could have specified a different location for these files by using the "Data Files" tab and "Transaction Log" tab. We also could have changed specifications on whether to allow the file to grow automatically (as it stores more and more data), and if so, how that growth should be managed.
1.
Ensuring you have the right database expanded, right click on the "Tables" icon and select "New Table...":
2.
While you have this screen open, do the following: a. b. Using the values in the screenshot, complete the details in the "Column Name" column, the "Data Type" column, "Length" column, and "Allow Nulls" column. Make the IndividualId column an "identity column", by setting "Identity" to "Yes" (just use the same values as in the screenshot). Note that to set values in the bottom pane, you need to select the column name in the top pane first). This column is going to be an auto-number column - it will contain an incrementing number for each record that is created.
c.
Set the "Default Value" of the DateCreated column to (getdate()). (This will automatically insert the current date into that field for each new record).
What we are doing at this stage, is creating the column names, specifying the type of data that can be entered into them, and setting default values. Restricting the data type for each column is very important and helps maintain data integrity. For example, it can prevent us from accidentally entering an email address into a field for storing the current date.
3.
1.
To open the table, right click on the table you wish to open, and select "Open Table > Return all rows":
2.
You can now start entering the data directly into your table.
When you're first learning SQL Server, this may not be a major concern. However, in an environment such as described, entering data directly into the table becomes quite inefficient.
Once you get used to writing and running scripts, you will probably find it quicker than entering data directly into the table.
6.
Accessing SQL Query Analyzer
You can open Query Analyzer from Enterprise Manager by clicking Tools > Query Analyzer.
Tip: Before you open Query Analyzer, use Enterprise Manager to navigate to the database you'd like to work with. That way, Query Analyzer will open using that database.
Object Browser
SQL Query Analyzer also has an "Object Browser" that you can use to browse and edit tables, views, and stored procedures. The Object Browser also displays a list of common SQL Server functions and their parameters.
To open the Object Browser, press F8. Alternatively, you can click the Object Browser icon
Browser is to go Tools > Object Browser > Show/hide. The Object Browser displays to the left of your workspace.
Writing Queries
You are now ready to write SQL queries against your database. You can use this interface to create database objects (such as databases, tables, views etc), insert data into a database table, select data, update data, delete data.
The following screen shot shows an example of using a SQL 'select' statement to select data from a database:
When I started creating the above example, I forgot the name of the table that I wanted to select data from. That wasn't a problem. All I needed to do was navigate through the Object Browser until I saw the names of the tables in the left pane. When I saw the table I needed, I simply clicked and dragged it onto the workspace area (and releasing the mouse in the right spot). This is quite a nice feature of Query Analyzer/Object Browser as it can save you time.
As you can see, the results of the query are displayed in the bottom pane.
The above 'select' statement is an example of a SQL query. Apart from the occasional example, SQL queries are outside the scope of this tutorial. If you'd like to learn more about writing SQL queries, check out the SQL tutorial.
Benefits of Views
A view can be useful when there are multiple users with different levels of access, who all need to see portions of the data in the database (but not necessarily all of the data). Views can do the following:
Restrict access to specific rows in a table Restrict access to specific columns in a table
Join columns from multiple tables and present them as though they are part of a single table Present aggregate information (such as the results of the COUNT function)
Creating a View
You create a view by using the CREATE VIEW statement, followed by the SELECT statement.
CREATE VIEW "Alphabetical list of products" AS SELECT Products.*, Categories.CategoryName FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID WHERE (((Products.Discontinued)=0))
Modifing a View
You can modify an existing view by using using ALTER instead or CREATE.
Example:
ALTER VIEW "Alphabetical list of products" AS SELECT Products.*, Categories.CategoryName FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID WHERE (((Products.Discontinued)=0))
Running a View
You run a view by using a SELECT statement.
A stored procedure is a precompiled group of Transact-SQL statements, and is saved to the database (under the "Stored Procedures" node). Programmers and administrators can execute stored procedures either from the Query Analyzer or from within an application as required.
Transact-SQL, which is based on SQL (Structured Query Language), is the programming language used to interface between applications and their databases. Transact-SQL is a relatively easy language to learn and I highly recommend becoming familiar with it.
Benefit
Explanation of benefit
Modular programming
You can write a stored procedure once, then call it from multiple places in your application.
Performance
Stored procedures provide faster code execution and reduce network traffic.
Faster execution: Stored procedures are parsed and optimized as soon as they are created and the stored procedure is stored in memory. This means that it will execute a lot faster than sending many lines of SQL code from your application to the SQL Server. Doing that requires SQL Server to compile and optimze your SQL code every time it runs.
Reduced network traffic: If you send many lines of SQL code over the network to your SQL Server, this will impact on network performance. This is especially true if you have hundreds of lines of SQL code and/or you have lots of activity on your application. Running the code on the SQL Server (as a stored procedure) eliminates the need to send this code over the network. The only network traffic will be the parameters supplied and the results of any query.
Security
Users can execute a stored procedure without needing to execute any of the statements directly. Therefore, a stored procedure can provide advanced database functionality for users who wouldn't normally have access to these tasks, but this functionality is made available in a tightly controlled way.
CREATE PROCEDURE MyStoredProcedure AS SET ROWCOUNT 10 SELECT Products.ProductName AS TenMostExpensiveProducts, Products.UnitPrice FROM Products ORDER BY Products.UnitPrice DESC
Once you run this code in the Query Analyzer, the stored procedure is created and appears under the "Stored Procedures" node.
EXEC MyStoredProcedure
If the stored procedure has spaces in its name, enclose it between double quotes:
configure security accounts set up linked servers create a database maintenance plan create full text search catalogs configure replication set up scheduled jobs and much more.
SQL Server has a number of security features that assist database administrators in maintaining their database in a secure way. You can see the areas of security by expanding the "Security" folder within Enterprise Manager.
Logins
SQL Server allows you to configure users and roles for anyone who needs to access SQL Server or any of its databases and their objects. Typically, you will have a database administrator who has access to everything. Then you will have users with varying levels of access, depending on the tasks they're allowed to perform.
Doing this can prevent inexperienced users from wreaking havoc on your database environment. Imagine if one morning you came to work, only to find that someone had accidentally deleted your main database!
In Enterprise Manager, you can use SQL Server Security section to restrict the tasks that each user can perform. If you have many users, you can assign them a role. Roles enable you to assign the same access rights across many users. Instead of assigning permissions against an individual user (or 'login'), you assign them against a role. You can then add users/logins into that role.
Server Roles
Server roles are available for various database administration tasks. Not everyone should be assigned to a server role. In fact, only advanced users such as database administrators should be assigned a server role.
Here are the server roles defined in SQL Server during setup:
Server Role
Description
sysadmin
serveradmin
Can set server-wide configuration options, can shut down the server.
setupadmin
securityadmin
Can manage logins and database permissions, read logs, change passwords.
processadmin
dbcreator
diskadmin
bulkadmin
As you can see, some of these roles allow very specific tasks to be performed. If you don't have many technical users, it's likely that you'll only use one or two of these roles (including sysadmin).
Linked Servers
The Linked Servers option allows you to connect to another instance of SQL Server running on a different machine, perhaps remotely in a different city/country. This can be useful if you need to perform distributed queries (query a remote database). Setting up a linked server is quite straight forward in Enterprise Manager, all you need is details of the remote server, and the database that you need to query.
In the above example, "Data Source" is the name of the SQL Server machine, "Catalogue" is the name of the database. You can also configure options in the other two tabs depending on your requirements.
Remote Servers
The Remote Servers option allows you to execute a stored procedure on another instance of SQL Server without establishing another connection. The Remote Servers option is only provided for backwards compatibility. If you need to execute stored procedures against a remote server, use a linked server.
2.
Tip: You can bypass the above steps by clicking on the "New Login" icon
3.
Complete the Login Properties in the "General" tab by providing a name for the login, choosing the Authentication method (providing a password if you choose "SQL Server Authentication"), and selecting the database to use as a default. If you don't choose language, it will use
4.
Click the "Server Roles" tab if you need to apply any server-wide security privileges.
5.
Click the "Database Access" tab to specify which databases this login is allowed to access. By default, the login will be assigned to the "Public" role, which provides the login with basic access. If the login needs more access in one or more databases, it can be assigned to another role with greater privileges.
Note that these roles are "Database Roles" and are different to the Server Roles in the previous tab. Server Roles are for administering the SQL Server. Database Roles are created within each database and specify what the login can do within that database.
11.DTS Tools
SQL Server DTS includes the following tools, which enable you to create, schedule, and execute DTS packages.
Tool
Description
DTS Designer
Enables you to build complex DTS packages containing workflow and event-driven logic. The DTS Designer can also be used to modify packages created with the DTS Import/Export Wizard.
dtsrun utility
Allows you to run DTS packages from the command prompt and schedule them using batch files.
1.
Using Enterprise Manager, right click on the "Data Transformation Services" node and select All Tasks > Import Data...
2.
3.
Select the Data Source - this is the file/database that contains the data we want to import. In this example, we are importing data from a Microsoft Access database, so we use the "Microsoft Access" option. We also specify the file name of the Access database as well as username and password if required.
4.
Select the Destination - this is the file/database that we want to import data into. In this example, we are importing data to our SQL Server database called "MyDatabase". We are also using Windows Authentication, but we could just have easily used one of the user accounts on our SQL database.
5.
Choose whether to copy one or more tables or to use a query to specify the data to transfer. In this example, we are going to copy a table and all its data.
6.
Select the table (or views) that you'd like to copy, and the name of the destination table. In this example, we'll use the default (a table will be created using the same name and data types as the source table).
You also have the option of clicking on "Transform" to change the column properties of the destination table. For example, you can change column names, data types, size etc. For now, we'll just leave it as is.
7.
Specify when to run this DTS package and whether to save it or not. In this example, we are going to run the package now. We have also chosen to save the DTS package.
8.
Because we have chosen to save this package, we need to specify details about the DTS package.
9.
10. And now, let's see if our DTS import was successful...
Well, now that we know our DTS import was successful, we can take a look at the table that was created. We can also have a look at our saved DTS package.
Our Table
DTS Designer
By selecting "Design Package" (see above screenshot), you can modify your saved DTS package using the DTS Designer. DTS Designer allows you to apply tasks, workflow and event driven logic against your DTS package. Here's what the DTS Designer looks like:
You don't really need to know that in order to use the SQL Agent Service though. You can configure SQL Server Agent jobs, alerts and operators via Enterprise Manager. Applications that use SQL-DMO or Transact-SQL with a standard database API can also do this, but for now, we'll stick with Enterprise Manager.
To start the SQL Server Agent Service via Enterprise Manager, right click on the "SQL Service Agent" node, and click "Start":
Now that SQL Server Agent is running, any jobs or alerts that you create will automatically run when they're supposed to.
13. Now that you know that the SQL Server Agent Service is responsible for ensuring any scheduled jobs are run at the specified time, let's create a
SQL Server Agent Job.
1.
From the "SQL Server Agent" node, right click on the "Jobs" node, and select "New Job":
2.
3.
4.
From the "Steps" tab, click "New" Complete the details for this step. In this example, we are using the dtsrun utility to execute a DTS package:
5.
6.
7.
8.
If you need to set a recurring schedule, click "Change" (from the previous screen) and complete the details:
Your SQL Agent Job has now been set up and is ready to run every morning at 2am, but don't forget to check that the SQL Server Agent Service is running!.
The reason I'm re-iterating this is because I have been caught out so many times with this. It's so easy to create a SQL job that its so easy to forget to check whether the SQL Server Agent is even running. Normally, in a production environment, the SQL Server Agent will be running constantly. In a development environment, you may choose to disable it until you need to test it.
To use the Service Manager, you can either right click on the icon, or double click on the icon. Right clicking provides a menu of options, double clicking maximizes the Service Manager for you to select your options.
15. SQL Profiler is a handy tool that enables you to monitor events within your SQL Server (or more specifically, a SQL Server instance). For example,
you could use SQL Profiler to check the performance of a stored procedure. You could also use SQL Profiler to troubleshoot a problem that's occuring in your production environment.
When using SQL Profiler, you can save the output to a "trace file" so that you can later analyze the events that occured during your trace.
1.
2.
To create a trace:
1. 2.
Open SQL Profiler as demonstrated above Select File > New > Trace... Select the SQL Server you'd like to connect to, provide authentication details, then click OK
3.
4.
In Trace Name field, enter a name for the trace, then set the other trace properties as required. For now, just use the default settings
5.
When you're ready to run the trace, click "Run". You will see something like this:
6.
When you're ready to stop the trace, click the "stop trace" icon
Following is a more detailed explanation of each tab on the Trace Properties screen.
The following table provides an explanation of the options on the General tab.
Field
Description
Trace name
Template name
This allows you to select a template to base the trace on. Templates provide you with a trace where the options from the Events, Data Columns, and Filters tabs are pre-configured. SQL Server includes a number of templates that you can use. SQLProfilerStandard is the default. The template you select will depend on the data you need from your trace. You can also create your own templates if required.
Save to file
Save to table
Allows you to specify a date and time for the trace to stop.
Transact-SQL SELECT, INSERT, UPDATE, and DELETE statements Locks being acquired/released Stored procedures being started/stopped A login connection/failure/disconnection A cursor being opened Errors written to the event log A remote procedure call (RPC) batch status Security permission checks
Try adding/removing events to see how this affects the trace output.
Note that the data columns that are available will depend on the event classes selected. This is because the event class determines the type of data available.
Also note that default data columns are selected automatically with all event classes.