0% found this document useful (0 votes)
189 views

SQL Server Questions

Microsoft SQL Server is a relational database management system developed by Microsoft that runs on Windows. It uses Transact-SQL as its query language. Some key releases include SQL Server 2005 in 2005 and SQL Server Express, a free and restricted version, in 2005. SQL Server runs as a service called sqlservr.exe and can be managed using tools like SQL Server Management Studio Express.

Uploaded by

jbk111
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
189 views

SQL Server Questions

Microsoft SQL Server is a relational database management system developed by Microsoft that runs on Windows. It uses Transact-SQL as its query language. Some key releases include SQL Server 2005 in 2005 and SQL Server Express, a free and restricted version, in 2005. SQL Server runs as a service called sqlservr.exe and can be managed using tools like SQL Server Management Studio Express.

Uploaded by

jbk111
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

What is Microsoft SQL Server?

Microsoft SQL Server is a relational database management system (RDBMS) developed by


Microsoft. It runs on Windows systems and uses Transact-SQL as the query language.

Microsoft SQL Server release history:


 1993 - SQL Server 4.21 for Windows NT
 1995 - SQL Server 6.0, codenamed SQL95
 1996 - SQL Server 6.5, codenamed Hydra
 1999 - SQL Server 7.0, codenamed Sphinx
 1999 - SQL Server 7.0 OLAP, codenamed Plato
 2000 - SQL Server 2000 32-bit, codenamed Shiloh (version 8.0)
 2003 - SQL Server 2000 64-bit, codenamed Liberty
 2005 - SQL Server 2005, codenamed Yukon (version 9.0)
 2005 - SQL Server 2005 Express Edition, restricted free version

 How to download Microsoft SQL Server 2005 Express Edition?


 Microsoft SQL Server 2005 Express Edition is the free version of the Microsoft SQL Server 2005.
If you are interested to try SQL Server 2005, you should follow this tutorial to download Microsoft
SQL Server 2005 Express Edition:
 1. Go to the Microsoft SQL Server 2005 Express Edition download page.
 2. Go to the Files in This Download section, and click Download button next to the
"SQLEXPR.EXE - 53.5 MB" file. The File Download box shows up.
 3. Save the download file to C:\temp directory. When the download is done, you should get the
following file:
 Name: SQLEXPR.EXE
 Description: Microsoft SQL 2005 Server Express Edition
 Location: C:\temp
 Size: 56,105,688 bytes
 Version: 9.0.1399.6
 What are the requirements to install SQL Server 2005 Express Edition?
 The following system requirements cover the SQL Server 2005 Express Edition:
 Processor
 32-bit Processor of 600-megahertz (MHz) or faster

 Operating System
 Windows XP with Service Pack 2 or later
 Windows 2000 Professional with SP4
 Windows 2000 Server with Service Pack 4 or later
 Windows Server 2003 Standard, or Enterprise SP1
 Windows Server 2003 Web Edition SP1
 Windows Small Business Server 2003 with SP1
 Vista Home Basic and above

 Framework
 .NET Framework 2.0

 Memory
 512 megabytes (MB) or more recommended

 Hard Disk
 Approximately 425 MB of available hard-disk space
 Why I am getting "The Microsoft .Net Framework 2.0 in not installed" message?
 When you try to install SQL Server 2005 Express Edition, you may get a Microsoft SQL Server
2005 Setup error box with this message: "The Microsoft .Net Framework 2.0 in not installed.
Please install before running setup."
 You are getting this error, because .NET Framework 2.0 is not installed on your system yet. Read
the next tutorial to download and install .NET Framework 2.0.
 How to download and install Microsoft .NET Framework Version 2.0?
 .NET Framework Version 2.0 is required by many Microsoft applications like SQL Server 2005. If
you want download and install .NET Framework Version 2.0, you should follow this turorial:
 1. Go to the Microsoft .NET Framework Version 2.0 Redistributable Package (x86) page.
 2. Click the Download button. Save the download file dotnetfx.exe to c:\temp.
 3. Look at and compare the downloaded file properties with:
 Name: dotnetfx.exe
 Location: C:\temp
 Size: 23,510,720 bytes
 Version: 2.0.50727.42
 4. Close all IE (Internet Explorer) windows.
 5. Double click the downloaded file: to c:\temp\dotnetfx.exe. The Microsoft .NET Framework 2.0
Setup windows shows up. Follow the intructions to finish the installtion.
 What is mscorsvw.exe - Process - Microsoft .NET Framework NGEN?
 Process mscorsvw.exe is installed as a system service as part of the .NET Framework 2.0. You
can disable it, if you are not using any applications that require .NET Framework 2.0.
 mscorsvw.exe process and program file info:
 CPU usage: 00%
 Memory usage: 2,704K
 Launching method: System Service
 Directory: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\
 File name: mscorsvw.exe
 Description: .NET Runtime Optimization Service
 Size: 66,240 bytes
 Date: Friday, September 23, 2005, 7:28:56 AM
 Version: 2.0.50727.42
 Company name: Microsoft
 System essential: No
 Virus/Spyware/Adware: No
 How to install SQL Server 2005 Express Edition?
 Once you have downloaded SQL Server 2005 Express Edition, you should follow this tutorial to
install it on your system:
 1. Double click SQLEXPR.EXE. The setup window shows up.
 2. Click Next to let the setup program to unpack all files from the downloaded file.
 3. When unpack is down, the setup program will check all required programs on your system.
 4. Then the setup program will start the installation process.
 5. On the Authentication Mode window, click the radio button for Mixed Mode (Windows
Authentication and SQL Server Authentication). And enter "FYIcenter" in the "Specify the sa
logon password below:" fields.
 6. Continue to finish the installation process.
 7. When installation is done, you will see a new program menu entry as: Start > Programs >
Microsoft SQL Server 2005 > Configuration Tools.
 How do you know if SQL Server is running on your local system?
 After installing SQL Server 2006 Express Edition, it will be running on your local system quietly as
a background process.
 If you want to see this process is running, run Windows Task Manager. You should see a process
called sqlservr.exe running in the process list:
 sqlservr.exe 00 1,316 K
 If you select sqlservr.exe and click the "End Process" button, SQL Server will be stopped.
 If you can not find sqlservr.exe in the process list, you know that your SQL Server is running.
 What is sqlservr.exe - Process - SQL Server (SQLEX?PRESS)
 Process sqlservr.exe is the Microsoft SQL Server system service installed as part of the Microsoft
SQL Server 2005 Express Dditon.
 mscorsvw.exe process and program file info:
 CPU usage: 00%
 Memory usage: 1,316K
 Launching method: System Service
 Directory: C:\Program Files\Microsoft SQL Server\MSSQL.1
 \MSSQL\Binn
 File name: sqlservr.exe
 Description: SQL Server Windows NT
 Size: 28,768,528 bytes
 Date: Friday, October 14, 2005, 3:51:46 AM
 Version: 2005.90.1399.0
 Company name: Microsoft
 System essential: No
 Virus/Spyware/Adware: No
 How to download and install Microsoft SQL Server Management Studio Express?
 Microsoft SQL Server Management Studio Express (SSMSE) is a free, easy-to-use graphical
management tool for managing SQL Server 2005 Express Edition and SQL Server 2005 Express
Edition with Advanced Services. If you want to download and install it to your system, follow this
tutorial:
 1. Go to SQL Server Management Studio Express home page.
 2. Go to the "Files in This Download" section.
 3. Click the Download button next to "SQLServer2005_SSMSEE.msi - 38.5 MB" And save it to
c:\temp directory.
 4. Look at and compare the downloaded file properties with:
 Name: SQLServer2005_SSMSEE.msi
 Location: C:\temp
 Size: 40,364,032 bytes
 5. Double click to install. The setup window shows up. Follow the instructions to finish the
installation process.
 6. When installation is done, you will see a new program menu entry as: Start > Programs >
Microsoft SQL Server 2005 > SQL Server Management Studio Express
 How to connect SQL Server Management Studio Express to SQL Server 2005 Express?
 Once you have SQL Server 2005 Express installed and running on your local machine, you are
ready to connect SQL Server Management Studio Express to the server:
 Click Start > Programs > Microsoft SQL Server 2005 > SQL Server Management Studio Express
to launch SQL Server Management Studio Express.
 The "Connect to Server" box shows up. The Server Name field has a default value of
"LOCALHOST\SQLEXPRESS". So don't change it. Select "SQL Server Authentication" as the
Authentication. Enter enter "sa" as the Login, and "FYIcenter" as the Password.

.
 Click the Connect button, you should see the SQL Server Management Studio Express window
comes up.
 How to run Queries with SQL Server Management Studio Express?
 1. Launch and connect SQL Server Management Studio Express to the local SQL Server 2005
Express.
 2. Click on the "New Query" button below the menu line. Enter the following SQL statement in the
query window:
 SELECT 'Welcome to FYIcenter.com SQL Server!'
 3. Click the Execute button in the toolbar area. You should get the following in the result window:
 Welcome to FYIcenter.com SQL Server!
 See the following picture to know where the query and result windows are:

.
 How to download and install SQL Server 2005 Books Online?
 1. Go to the SQL Server 2005 Books Online download page.
 2. Click the download button, the File Download box shows up. Save the download file to c:\temp.
 3. Double click on the downloaded file: c:\temp\SqlServer2K5_BOL_Feb2007.msi. The
installation setup window shows up. Follow the instructions to finish the installation.
 4. When the installation is done. You will see a new entry in the Start menu: Start > Programs >
Microsoft SQL Server 2005 > Documentation and Tutorials
 How to run SQL Server 2005 Books Online on your local system?
 SQL Server 2005 Books Online can be accessed by a Web browser over the Internet. But you
can also download it and read it on your local system. If you have downloaded and installed SQL
Server 2005 Books Online package, you follow this tutorial to run it:
 1. Click Start > Programs > Microsoft SQL Server 2005 > Documentation and Tutorials >
Tutorials > SQL Server Tutorials. The SQL Server 2005 Books Online window shows up.
 2. Click the plus sign (+) next to "SQL Server 2005 Tutorials in the Contents window".
 3. Click the plus sign (+) next to "SQL Server Tools Tutorials".
 4. Click "Lesson 1: Basic Navigation in SQL Server Management Studio". The book content
shows up for you to read.

.
 How to use Transact-SQL statements to access the database engine?
 Transact-SQL statements can be used to access the database engine directly. Here are some
good tutorials provided by the SQL Server 2005 Books Online. See the SQL Server 2005
Tutorials > Database Engine Tutorials > Writing Transact-SQL Statements Tutorial section in the
SQL Server 2005 Books Online document.
 This tutorial is intended for users who are new to writing SQL statements. It will help new users
get started by reviewing some basic statements for creating tables and inserting data. This
tutorial uses Transact-SQL, the Microsoft implementation of the SQL standard. This tutorial is
intended as a brief introduction to the Transact-SQL language and not as a replacement for a
Transact-SQL class. The statements in this tutorial are intentionally simple, and are not meant to
represent the complexity found in a typical production database.
 How to create new databases with "CREATE DATABASE" statements?
 This is the first tutorial of a quick lesson on creating database objects with Transact-SQL
statements. This lesson shows you how to create a database, create a table in the database, and
then access and change the data in the table. Because this lesson is an introduction to using
Transact-SQL, it does not use or describe the many options that are available for these
statements. This tutorial assumes that you are running SQL Server Management Studio Express.
 Like many Transact-SQL statements, the CREATE DATABASE statement has a required
parameter: the name of the database. CREATE DATABASE also has many optional parameters,
such as the disk location where you want to put the database files. When you execute CREATE
DATABASE without the optional parameters, SQL Server uses default values for many of these
parameters. This tutorial uses very few of the optional syntax parameters.
 To create a database - In a Query Editor window, type but do not execute the following code:
 CREATE DATABASE TestData
 GO
 Use the pointer to select the words CREATE DATABASE, and then press F1. The CREATE
DATABASE topic in SQL Server 2005 Books Online should open. You can use this technique to
find the complete syntax for CREATE DATABASE and for the other statements that are used in
this tutorial.
 In Query Editor, press F5 to execute the statement and create a database named TestData.
When you create a database, SQL Server makes a copy of the model database, and renames
the copy to the database name. This operation should only take several seconds, unless you
specify a large initial size of the database as an optional parameter.
 How to create new table with "CREATE TABLE" statements?
 This is the second tutorial of a quick lesson on creating database objects with Transact-SQL
statements. This lesson shows you how to create a database, create a table in the database, and
then access and change the data in the table. Because this lesson is an introduction to using
Transact-SQL, it does not use or describe the many options that are available for these
statements. This tutorial assumes that you are running SQL Server Management Studio Express.
 To create a table, you must provide a name for the table, and the names and data types of each
column in the table. It is also a good practice to indicate whether null values are allowed in each
column.
 Most tables have a primary key, made up of one or more columns of the table. A primary key is
always unique. The Database Engine will enforce the restriction that any primary key value
cannot be repeated in the table.
 For a list of data types and links for a description of each, see Data Types (Transact-SQL).
 Note: The Database Engine can be installed as case sensitive or non-case sensitive. If the
Database Engine is installed as case sensitive, object names must always have the same case.
For example, a table named OrderData is a different table from a table named ORDERDATA. If
the Database Engine is installed as non-case sensitive, those two table names are considered to
be the same table, and that name can only be used one time.
 Before you create the table in this tutorial, execute the USE command to change the database
context to the TestData database. Otherwise, you will create the table in the database you were
connected to earlier. That was probably your default database. Unless your default database has
been changed, the default database is the master database. You should not create objects in the
master database.
 Switch the Query Editor connection to the TestData database - In a Query Editor window,
type and execute the following code to change your connection to the TestData database.
 USE TestData
 GO
 To create a table - In a Query Editor window, type and execute the following code to create a
simple table named Products. The columns in the table are named ProductID, ProductName,
Price, and ProductDescription. The ProductID column is the primary key of the table. int,
varchar(25), money, and text are all data types. Only the Price and ProductionDescription
columns can have no data when a row is inserted or changed. This statement contains an
optional element (dbo.) called a schema. The schema is the database object that owns the table.
If you are an administrator, dbo is the default schema. dbo stands for database owner.
 CREATE TABLE dbo.Products
 (ProductID int PRIMARY KEY NOT NULL,
 ProductName varchar(25) NOT NULL,
 Price money NULL,
 ProductDescription text NULL)
 GO
 How to insert and update data into a table with "INSERT" and "UPDATE" statements?
 This is the third tutorial of a quick lesson on creating database objects with Transact-SQL
statements. This lesson shows you how to create a database, create a table in the database, and
then access and change the data in the table. Because this lesson is an introduction to using
Transact-SQL, it does not use or describe the many options that are available for these
statements. This tutorial assumes that you are running SQL Server Management Studio Express.
 Now that you have created the Products table, you are ready to insert data into the table by using
the INSERT statement. After the data is inserted, you will change the content of a row by using
an UPDATE statement. You will use the WHERE clause of the UPDATE statement to restrict the
update to a single row. The four statements will enter the following data.
ProductID ProductName Price ProductDescription
1 Clamp 12.48 Workbench clamp
50 Screwdriver 3.17 Flat head
75 Tire Bar Tool for changing tires
3000 3mm Bracket .52

 The basic syntax is: INSERT, table name, column list, VALUES, and then a list of the values to
be inserted. The two hyphens in front of a line indicate that the line is a comment and the text will
be ignored by the compiler. In this case, the comment describes a permissible variation of the
syntax.
 To insert data into a table - Execute the following statement to insert a row into the Products
table that was created in the previous task. This is the basic syntax.
 -- Standard syntax
 INSERT dbo.Products (ProductID, ProductName, Price, ProductDescription)
 VALUES (1, 'Clamp', 12.48, 'Workbench clamp')
 GO
 The following statement shows how you can change the order in which the parameters are
provided by switching the placement of the ProductID and ProductName in both the field list (in
parentheses) and in the values list.
 -- Changing the order of the columns
 INSERT dbo.Products (ProductName, ProductID, Price, ProductDescription)
 VALUES ('Screwdriver', 50, 3.17, 'Flat head')
 GO
 The following statement demonstrates that the names of the columns are optional, as long as the
values are listed in the correct order. This syntax is common but is not recommended because it
might be harder for others to understand your code. NULL is specified for the Price column
because the price for this product is not yet known.
 -- Skipping the column list, but keeping the values in order
 INSERT dbo.Products
 VALUES (75, 'Tire Bar', NULL, 'Tool for changing tires.')
 GO
 The schema name is optional as long as you are accessing and changing a table in your default
schema. Because the ProductDescription column allows null values and no value is being
provided, the ProductDescription column name and value can be dropped from the statement
completely.
 -- Dropping the optional dbo and dropping the ProductDescription column
 INSERT Products (ProductID, ProductName, Price)
 VALUES (3000, '3mm Bracket', .52)
 GO
 To update the products table - Type and execute the following UPDATE statement to change
the ProductName of the second product from Screwdriver, to Flat Head Screwdriver.
 UPDATE dbo.Products
 SET ProductName = 'Flat Head Screwdriver'
 WHERE ProductID = 50
 GO
 How to read data in a table with "SELECT" statements?
 This is the fourth tutorial of a quick lesson on creating database objects with Transact-SQL
statements. This lesson shows you how to create a database, create a table in the database, and
then access and change the data in the table. Because this lesson is an introduction to using
Transact-SQL, it does not use or describe the many options that are available for these
statements. This tutorial assumes that you are running SQL Server Management Studio Express.
 Use the SELECT statement to read the data in a table. The SELECT statement is one of the most
important Transact-SQL statements, and there are many variations in the syntax. For this tutorial,
you will work with five simple versions.
 To read the data in a table - Type and execute the following statements to read the data in the
Products table.
 -- The basic syntax for reading data from a single table
 SELECT ProductID, ProductName, Price, ProductDescription
 FROM dbo.Products
 GO
 You can use an asterisk to select all the columns in the table. This is often used in ad hoc
queries. You should provide the column list in you permanent code so that the statement will
return the predicted columns, even if a new column is added to the table later.
 -- Returns all columns in the table
 -- Does not use the optional schema, dbo
 SELECT * FROM Products
 GO
 You can omit columns that you do not want to return. The columns will be returned in the order
that they are listed.
 -- Returns only two of the columns from the table
 SELECT ProductName, Price
 FROM dbo.Products
 GO
 Use a WHERE clause to limit the rows that are returned to the user.
 -- Returns only two of the records in the table
 SELECT ProductID, ProductName, Price, ProductDescription
 FROM dbo.Products
 WHERE ProductID < 60
 GO
 You can work with the values in the columns as they are returned. The following example
performs a mathematical operation on the Price column. Columns that have been changed in this
way will not have a name unless you provide one by using the AS keyword.
 -- Returns ProductName and the Price including a 7% tax
 -- Provides the name CustomerPays for the calculated column
 SELECT ProductName, Price * 1.07 AS CustomerPays
 FROM dbo.Products
 GO
 How to create a login to access the database engine using "CREATE LOGIN" statements?
 This is the first tutorial of a quick lesson on creating login and configure users for databases with
Transact-SQL statements. Granting a user access to a database involves three steps. First, you
create a login. The login lets the user connect to the SQL Server Database Engine. Then you
configure the login as a user in the specified database. And finally, you grant that user permission
to database objects. This lesson shows you these three steps, and shows you how to create a
view and a stored procedure as the object. This tutorial assumes that you are running SQL
Server Management Studio Express.
 To access the Database Engine, users require a login. The login can represent the user's identity
as a Windows account or as a member of a Windows group, or the login can be a SQL Server
login that exists only in SQL Server. Whenever possible you should use Windows Authentication.
 By default, administrators on your computer have full access to SQL Server. For this lesson, we
want to have a less privileged user; therefore, you will create a new local Windows Authentication
account on your computer. To do this, you must be an administrator on your computer. Then you
will grant that new user access to SQL Server. The following instructions are for Windows XP
Professional.
 To create a new Windows account - Click Start, click Run, in the Open box, type %SystemRoot
%\system32\compmgmt.msc /s, and then click OK to open the Computer Management program.
 Under System Tools, expand Local Users and Groups, right-click Users, and then click New
User.
 In the User name box type Mary.
 In the Password and Confirm password box, type a strong password, and then click Create to
create a new local Windows user.
 To create a login - In a Query Editor window of SQL Server Management Studio, type and
execute the following code replacing computer_name with the name of your computer. FROM
WINDOWS indicates that Windows will authenticate the user. The optional
DEFAULT_DATABASE argument connects Mary to the TestData database, unless her
connection string indicates another database. This statement introduces the semicolon as an
optional termination for a Transact-SQL statement.
 CREATE LOGIN [computer_name\Mary]
 FROM WINDOWS
 WITH DEFAULT_DATABASE = [TestData];
 GO
 This authorizes a user name Mary, authenticated by your computer, to access this instance of
SQL Server. If there is more than one instance of SQL Server 2005 on the computer, you must
create the login on each instance that Mary must access.
 How to create a user to access a database using "CREATE USER" statements?
 This is the second tutorial of a quick lesson on creating login and configure users for databases
with Transact-SQL statements. Granting a user access to a database involves three steps. First,
you create a login. The login lets the user connect to the SQL Server Database Engine. Then you
configure the login as a user in the specified database. And finally, you grant that user permission
to database objects. This lesson shows you these three steps, and shows you how to create a
view and a stored procedure as the object. This tutorial assumes that you are running SQL
Server Management Studio Express.
 Mary now has access to this instance of SQL Server 2005, but does not have permission to
access the databases. She does not even have access to her default database TestData until
you authorize her as a database user.
 To grant Mary access, switch to the TestData database, and then use the CREATE USER
statement to map her login to a user named Mary.
 To create a user in a database - Type and execute the following statements (replacing
computer_name with the name of your computer) to grant Mary access to the TestData database.

 USE [TestData];
 GO

 CREATE USER [Mary] FOR LOGIN [computer_name\Mary];
 GO
 Now, Mary has access to both SQL Server 2005 and the TestData database
 How to create a view and a stored procedure using "CREATE VIEW/PROCEDURE"
statements?
 This is the third tutorial of a quick lesson on creating login and configure users for databases with
Transact-SQL statements. Granting a user access to a database involves three steps. First, you
create a login. The login lets the user connect to the SQL Server Database Engine. Then you
configure the login as a user in the specified database. And finally, you grant that user permission
to database objects. This lesson shows you these three steps, and shows you how to create a
view and a stored procedure as the object. This tutorial assumes that you are running SQL
Server Management Studio Express.
 Now that Mary can access the TestData database, you may want to create some database
objects, such as a view and a stored procedure, and then grant Mary access to them. A view is a
stored SELECT statement, and a stored procedure is one or more Transact-SQL statements that
execute as a batch.
 Views are queried like tables and do not accept parameters. Stored procedures are more
complex than views. Stored procedures can have both input and output parameters and can
contain statements to control the flow of the code, such as IF and WHILE statements. It is good
programming practice to use stored procedures for all repetitive actions in the database.
 For this example, you will use CREATE VIEW to create a view that selects only two of the
columns in the Products table. Then, you will use CREATE PROCEDURE to create a stored
procedure that accepts a price parameter and returns only those products that cost less than the
specified parameter value.
 To create a view - Execute the following statement to create a very simple view that executes a
select statement, and returns the names and prices of our products to the user.

 CREATE VIEW vw_Names
 AS
 SELECT ProductName, Price FROM Products;
 GO
 Test the view - Views are treated just like tables. Use a SELECT statement to access a view.

 SELECT * FROM vw_Names;
 GO
 To create a stored procedure - The following statement creates a stored procedure name
pr_Names, accepts an input parameter named @VarPrice of data type money. The stored
procedure prints the statement Products less than concatenated with the input parameter that is
changed from the money data type into a varchar(10) character data type. Then, the procedure
executes a SELECT statement on the view, passing the input parameter as part of the WHERE
clause. This returns all products that cost less than the input parameter value.

 CREATE PROCEDURE pr_Names @VarPrice money
 AS
 BEGIN
 -- The print statement returns text to the user
 PRINT 'Products less than ' + CAST(@VarPrice AS varchar(10));
 -- A second statement starts here
 SELECT ProductName, Price FROM vw_Names
 WHERE Price < @varPrice;
 END
 GO
 Test the stored procedure - To test the stored procedure, type and execute the following
statement. The procedure should return the names of the two products entered into the Products
table in Lesson 1 with a price that is less than 10.00.

 EXECUTE pr_Names 10.00;
 GO
 How to grant a permission using "GRANT EXECUTE" statements?
 This is the fourth tutorial of a quick lesson on creating login and configure users for databases
with Transact-SQL statements. Granting a user access to a database involves three steps. First,
you create a login. The login lets the user connect to the SQL Server Database Engine. Then you
configure the login as a user in the specified database. And finally, you grant that user permission
to database objects. This lesson shows you these three steps, and shows you how to create a
view and a stored procedure as the object. This tutorial assumes that you are running SQL
Server Management Studio Express.
 As an administrator, you can execute the SELECT from the Products table and the vw_Names
view, and execute the pr_Names procedure; however, Mary cannot. To grant Mary the necessary
permissions, use the GRANT statement.
 Procedure Title - Execute the following statement to give Mary the EXECUTE permission for the
pr_Names stored procedure.

 GRANT EXECUTE ON pr_Names TO Mary;
 GO
 In this scenario, Mary can only access the Products table by using the stored procedure. If you
want Mary to be able to execute a SELECT statement against the view, then you must also
execute GRANT SELECT ON vw_Names TO Mary. To remove access to database objects, use
the REVOKE statement.
 Note: If the table, the view, and the stored procedure are not owned by the same schema,
granting permissions becomes more complex. For information about how to configure
permissions on objects with different owners, see Ownership Chains.
 About GRANT You must have EXECUTE permission to execute a stored procedure. You must
have SELECT, INSERT, UPDATE, and DELETE permissions to access and change data. The
GRANT statement is also used for other permissions, such as permission to create tables.
 How to delete database objects with "DROP" statements?
 To remove all database objects created by previous tutorials, you could just delete the database.
However, in this tutorial, you will go through the steps to reverse every action you took doing the
tutorial.
 Removing permissions and objects - Before you delete objects, make sure you are in the
correct database:
 USE TestData;
 GO
 Use the REVOKE statement to remove execute permission for Mary on the stored procedure:
 REVOKE EXECUTE ON pr_Names FROM Mary;
 GO
 Use the DROP statement to remove permission for Mary to access the TestData database:
 DROP USER Mary;
 GO
 Use the DROP statement to remove permission for Mary to access this instance of SQL Server
2005:
 DROP LOGIN [\Mary];
 GO
 Use the DROP statement to remove the store procedure pr_Names:
 DROP PROC pr_Names;
 GO
 Use the DROP statement to remove the view vw_Names:
 DROP View vw_Names;
 GO
 Use the DELETE statement to remove all rows from the Products table:
 DELETE FROM Products;
 GO
 Use the DROP statement to remove the Products table:
 DROP Table Products;
 GO
 You cannot remove the TestData database while you are in the database; therefore, first switch
context to another database, and then use the DROP statement to remove the TestData
database:
 USE MASTER;
 GO
 DROP DATABASE TestData;
 GO

What is a database?

A database is a logical container that contains a set of related database objects:


 Tables - Storages of structured data.
 Views - Queries to present data from tables.
 Indexes - Sorting indexes to speed up searches.
 Stored Procedures - Predefined SQL program units.
 Users - Identifications used for data access control.
 Other objects.

 What is the simplest way to create a new database?


 The simplest way to create a new database is to use the "CREATE DATABASE" statement with
this syntax:
 CREATE DATABASE database_name
 For example, run this statement:
 CREATE DATABASE FyiCenterData
 GO
 A new database called "FyiCenterData" should be created in the SQL server. Of course,
FyiCenterData should be empty at this moment - no tables. But it should have some other data
objects automatically created by the server.
 How to set the current database?
 Once you are connected to the SQL Server, you should select a database to work with and set it
as the current database using the "USE" statement with this syntax:
 USE database_name
 The following tutorial example shows you how to set "FyiCenterData" as the current database,
and create a table in "FyiCenterData":
 USE FyiCenterData
 GO
 Changed database context to 'FyiCenterData'.

 CREATE TABLE Links (Name NVARCHAR(32))
 GO

 SELECT name, type_desc, create_date FROM sys.tables
 GO
 name type_desc create_date
 Links USER_TABLE 2007-05-19 23:05:43.700
 How to delete a database?
 If you created a database incorrectly, or you have a database that is not needed any more, you
can delete it with the "DROP DATABASE" statement with this syntax:
 DROP DATABASE database_name
 For example, execute this statement:
 DROP DATABASE FyiCenterData
 GO
 The database "FyiCenterData" created in the previous tutorial should be deleted from the SQL
server.
 Warning, if you delete a database, all tables and their data in that database will be deleted.
 Why I am getting this error when dropping a database?
 If you are trying to drop a database that is in use, you will get an error message like this: 'Cannot
drop database "FyiCenterData" because it is currently in use.'
 Before dropping a database, you must stop all client sessions using this database. If your own
client session is using this database, you should set a different database as the current database
as shown in this tutorial example:
 CREATE DATABASE FyiCenterData
 GO

 USE FyiCenterData
 GO

 DROP DATABASE FyiCenterData
 GO
 Msg 3702, Level 16, State 4, Server LOCALHOST\SQLEXPRESS
 Cannot drop database "FyiCenterData" because it is
 currently in use.

 USE master
 GO

 DROP DATABASE FyiCenterData
 GO
 How to get a list all databases on the SQL server?
 If you don't remember database names you have created, you can get a list of all databases on
the server by query the "sys.databases" view as shown in this tutorial example:
 CREATE DATABASE FyiCenterData
 GO

 SELECT name, database_id, create_date FROM sys.databases
 GO
 name database_id create_date
 master 1 2003-04-08 09:13:36.390
 tempdb 2 2007-05-19 13:42:42.200
 model 3 2003-04-08 09:13:36.390
 msdb 4 2005-10-14 01:54:05.240
 FyiCenterData 5 2007-05-19 20:04:39.310
 As you can see, the newly created database is listed at the end of query result

Where is my database stored on the hard disk?


If a database is created with simple CREATE DATABASE statement, the server will create two
database files on the hard disk to store data and configuration information about that data bases:
 database_name.mdf - SQL Server Database Primary Data File
 database_name_log.ldf - SQL Server Database Transaction Log File

To find out the location of database files, you can query the "sys.database_files" view as shown in
this tutorial example:
USE FyiCenterData
GO

SELECT type_desc, physical_name, size


FROM sys.database_files
GO
type_desc physical_name size

ROWS c:\Program Files\Microsoft SQL Server


\MSSQL.1\MSSQL\DATA\FyiCenterData.mdf 152

LOG c:\Program Files\Microsoft SQL Server


\MSSQL.1\MSSQL\DATA\FyiCenterData_log.LDF 63

Go verify these two files with Windows Explorer.

How to create database with physical files specified?

If you don't like the default behavior of the CREATE DATABASE statement, you can specify the
physical database files with a longer statement:
CREATE DATABASE database_name
ON (NAME = logical_data_name,
FILENAME = physical_data_name,
SIZE = x, MAXSIZE = y, FILEGROWTH = z)
LOG ON (NAME = logical_log_name,
FILENAME = physical_log_name,
SIZE = x, MAXSIZE = y, FILEGROWTH = z)

For example, the following statement will create a database with database files located in the C:\temp
directory:
USE master
GO

DROP DATABASE FyiCenterData


GO

CREATE DATABASE FyiCenterData


ON (NAME = FyiCenterData,
FILENAME = 'C:\temp\FyiCenterData.mdf',
SIZE = 10MB, MAXSIZE = 50MB, FILEGROWTH = 5MB)
LOG ON (NAME = FyiCenterLog,
FILENAME = 'C:\temp\FyiCenterLog.ldf',
SIZE = 1MB, MAXSIZE = 5MB, FILEGROWTH = 1MB)
GO

SELECT type_desc, name, physical_name, size


FROM sys.database_files
GO
type_desc name physical_name size
ROWS FyiCenterData C:\temp\FyiCenterData.mdf 1280
LOG FyiCenterLog C:\temp\FyiCenterLog.ldf 128

How to rename databases?

If don't like the name of a database, you can change it by using the "ALTER DATABASE" statement
with the following syntax:
ALTER DATABASE database_name
MODIFY NAME = new_database_name

The tutorial example below shows you how change the database name from "FyiCenterData" to
"FyiCenterComData":
ALTER DATABASE FyiCenterData
MODIFY NAME = FyiCenterComData
GO
The database name 'FyiCenterComData' has been set

Why I am getting this error when renaming a database?

If you are trying to rename a database that is in use, you will get an error message like this: "The
database could not be exclusively locked to perform the operation."

Before renaming a database, you must stop all client sessions using this database. Otherwise, you
will get an error as shown in this tutorial example:

1. Launch one instance of SQL Server Management Studio and run:


USE FyiCenterComData
GO

2. Keep the first instance running and launch another instance of SQL Server Management Studio:
ALTER DATABASE FyiCenterComData
MODIFY NAME = FyiCenterData
GO
Msg 5030, Level 16, State 2, Server LOCALHOST\SQLEXPRESS
The database could not be exclusively locked to perform
the operation.

Obviously, the first instance is blocking the "ALTER DATABASE" statement.


What are database states?

A database is always in one specific state. For example, these states include ONLINE, OFFLINE, or
SUSPECT. To verify the current state of a database, select the state_desc column in the
sys.databases catalog view. The following table defines the database states.
 ONLINE - Database is available for access. The primary filegroup is online, although the undo
phase of recovery may not have been completed.
 OFFLINE - Database is unavailable. A database becomes offline by explicit user action and
remains offline until additional user action is taken. For example, the database may be taken
offline in order to move a file to a new disk. The database is then brought back online after the
move has been completed.
 RESTORING - One or more files of the primary filegroup are being restored, or one or more
secondary files are being restored offline. The database is unavailable.
 RECOVERING - Database is being recovered. The recovering process is a transient state; the
database will automatically become online if the recovery succeeds. If the recovery fails, the
database will become suspect. The database is unavailable.
 RECOVERY PENDING - SQL Server has encountered a resource-related error during recovery.
The database is not damaged, but files may be missing or system resource limitations may be
preventing it from starting. The database is unavailable. Additional action by the user is required
to resolve the error and let the recovery process be completed.
 SUSPECT - At least the primary filegroup is suspect and may be damaged. The database cannot
be recovered during startup of SQL Server. The database is unavailable. Additional action by the
user is required to resolve the problem.
 EMERGENCY - User has changed the database and set the status to EMERGENCY. The
database is in single-user mode and may be repaired or restored. The database is marked
READ_ONLY, logging is disabled, and access is limited to members of the sysadmin fixed server
role. EMERGENCY is primarily used for troubleshooting purposes. For example, a database
marked as suspect can be set to the EMERGENCY state. This could permit the system
administrator read-only access to the database.

 How to set a database state to OFFLINE?


 If you want to move database physical files, you should take the database offline by using the
"ALTER DATABASE" statement with the following syntax:
 ALTER DATABASE database_name SET OFFLINE
 The following tutorial example will bring "FyiCenterComData" offline:
 ALTER DATABASE FyiCenterComData SET OFFLINE
 GO

 SELECT name, state_desc from sys.databases
 GO
 name state_desc
 master ONLINE
 tempdb ONLINE
 model ONLINE
 msdb ONLINE
 FyiCenterComData OFFLINE

 USE FyiCenterComData
 GO
 Msg 942, Level 14, State 4, Line 1
 Database 'FyiCenterComData' cannot be opened because
 it is offline.
 How to move database physical files?
 If you want to move database physical files to a new location, you can use the "ALTER
DATABASE" statements to bring the database offline, and link it to the files at the new location.
The following tutorial gives you a good example:
 ALTER DATABASE FyiCenterComData SET ONLINE
 GO

 USE FyiCenterComData
 GO

 CREATE TABLE Links (Name NVARCHAR(32))
 GO

 ALTER DATABASE FyiCenterComData SET OFFLINE
 GO
 Now it is safe to move the database physical files to a new location:
 1. Run Windows Explorer
 2. Create a new directory: c:\temp\data
 3. Drag and drop c:\temp\FyiCenterData.mdf to c:\temp\data
 3. Drag and drop c:\temp\FyiCenterLog.mdf to c:\temp\data
 Go back to the SQL client program and run:
 ALTER DATABASE FyiCenterComData
 MODIFY FILE (NAME = FyiCenterData,
 FILENAME = 'C:\temp\data\FyiCenterData.mdf')
 GO
 The file "FyiCenterData" has been modified in the system
 catalog. The new path will be used the next time the
 database is started.

 ALTER DATABASE FyiCenterComData
 MODIFY FILE (NAME = FyiCenterLog,
 FILENAME = 'C:\temp\data\FyiCenterLog.ldf')
 GO
 The file "FyiCenterLog" has been modified in the system
 catalog. The new path will be used the next time the
 database is started.

 ALTER DATABASE FyiCenterComData SET ONLINE
 GO

 USE FyiCenterComData
 GO

 SELECT type_desc, name, physical_name, size
 FROM sys.database_files
 GO
 type_desc name physical_name size
 ROWS FyiCenterData C:\temp\data\FyiCenterData.mdf 1280
 LOG FyiCenterLog C:\temp\data\FyiCenterLog.ldf 128

 SELECT name, type_desc FROM sys.tables
 GO
 name type_desc
 Links USER_TABLE
 As you can see the physical files are moved properly, and the "Links" table is still there

How to set database to be READ_ONLY?

Databases in SQL Server have two update options:


 READ_WRITE - Data objects are allowed to be queried and modified. This is the default.
 READ_ONLY - Data objects are allowed to be queried, but not allowed to be modified.

You can use the "ALTER DATABASE" to change database update options as shown in the tutorial
below:
USE FyiCenterComData
GO

INSERT Links (Name) VALUES ('dba.FYIcenter.com')


GO
(1 rows affected)

ALTER DATABASE FyiCentercomData SET READ_ONLY


GO

INSERT Links (Name) VALUES ('dev.FYIcenter.com')


GO
Msg 3906, Level 16, State 1, Server SQLEXPRESS, Line 1
Failed to update database "FyiCenterComData" because
the database is read-only.

SELECT * FROM Links


GO
Name
dba.FYIcenter.com

ALTER DATABASE FyiCentercomData SET READ_WRITE


GO

INSERT Links (Name) VALUES ('dev.FYIcenter.com')


GO
(1 rows affected)

As you can see from the output, inserting data into a table is not allowed if the database is in
READ_ONLY mode.
How to set database to be SINGLE_USER?

Databases in SQL Server have three user access options:


 MULTI_USER - All users that have the appropriate permissions to connect to the database are
allowed. This is the default.
 SINGLE_USER - One user at a time is allowed to connect to the database. All other user
connections are broken.
 RESTRICTED_USER - Only members of the db_owner fixed database role and dbcreator and
sysadmin fixed server roles are allowed to connect to the database, but it does not limit their
number.

You can use the "ALTER DATABASE" to change database user access options as shown in the
tutorial below:
USE FyiCenterComData
GO

ALTER DATABASE FyiCentercomData SET SINGLE_USER


GO

Now connect to server with another client session and try:


USE FyiCenterComData
GO
Msg 924, Level 14, State 1, Line 1
Database 'FyiCenterComData' is already open and can only
have one user at a time.

Go back to the first session and re-set the database to MULTI_USER:


ALTER DATABASE FyiCenterComData SET MULTI_USER
GO

What are system databases?

System databases are created by the SQL Server itself during the installation process. System
databases are used by the SQL server to help manage other user databases and client execution
sessions. SQL Server 2005 Express Edition uses 4 system databases:
 master - The brain of a SQL server - Stores server configuration, runtime information, and
database metadata.
 model - An empty database model - Used to clone new databases.
 msdb - The background job scheduler - Used for background jobs and related tasks.
 tempdb - The temporary database - Used by the server as a scratch pad.

What is a table?

A table in database is a data object used to store data. Tables have the following features:
 Data is stored in a table with a structure of rows and columns.
 Columns must be pre-defined with names, types and constrains.
 A table object may have other associated data objects like, constrains, triggers, indexes, and
statistics.
For example, a table called Address may have columns defined to store different elements of an
address like, street number, city, country, postal code, etc.

What are DDL (Data Definition Language) statements for tables?

DDL (Data Definition Language) statements are statements to create and manage data objects in the
database. The are three primary DDL statements to create and manage tables:
 CREATE TABLE - Creating a new table.
 ALTER TABLE - Altering the definition of an existing table.
 DROP TABLE - Dropping an existing table.

 How to create new tables with "CREATE TABLE" statements?


 If you want to create a new table, you can use the "CREATE TABLE" statement. The following
tutorial script shows you how to create a table called "tip":
 CREATE TABLE tip (id INTEGER PRIMARY KEY,
 subject VARCHAR(80) NOT NULL,
 description VARCHAR(256) NOT NULL,
 create_date DATETIME NULL)
 GO
 This scripts creates a testing table called "tip" with 4 columns in the current database.
 How To Get a List of All Tables with "sys.tables" View?
 If you want to see the table you have just created, you can use the "sys.tables" system view to
get a list of all tables in the current database. The tutorial script gives you a good example:
 SELECT name, type_desc, create_date FROM sys.tables
 GO
 name type_desc create_date
 tip USER_TABLE 2007-05-19 23:05:43.700
 The output shows that there is only one table in the current database.
 How To Get a List of Columns using the "sys.columns" View?
 If you have an existing table, but you don't remember what are the columns defined in the table,
you can use the "sys.columns" system view to get a list of all columns of all tables in the current
database.
 In order to a list of columns of a single table, you need to join sys.columns and sys.tables as
shown in the tutorial example below:
 SELECT * FROM sys.columns c, sys.tables t
 WHERE c.object_id = t.object_id
 AND t.name = 'tip'
 GO
 object_id name column_id user_type_id max_length
 2073058421 id 1 56 4
 2073058421 subject 2 167 80
 2073058421 description 3 167 256
 2073058421 create_date 4 61 8
 You can see the column names easily from the sys.columns view. But you can only see the
column type IDs. This requires another join to get the column type names. You may try the
"sp_columns" stored procedure to get a better list of columns shown in the next tutorial.
 How To Get a List of Columns using the "sp_columns" Stored Procedure?
 If you have an existing table, but you don't remember what are the columns defined in the table,
you can use the "sp_columns" stored procedure to get a list of all columns of the specified table.
The following tutorial script shows you a good example:
 sp_columns tip
 GO
 TABLE_OWNER TABLE_NAME COLUMN_TABLE TYPE_NAME ...
 dbo tip id int ...
 dbo tip subject varchar ...
 dbo tip description varchar ...
 dbo tip create_date datetime ...
 The "sp_columns" stored procedure returns a long list of properties for each column of the
specified table. Take a look at each of them.
 How To Get a List of Columns using the "sp_help" Stored Procedure?
 Another way to get a list of columns from a table is to use the "sp_help" stored procedure.
"sp_help" returns more than just a list of columns. It returns: the table information, the column
information, the identity column, the row GUID column, the primary key, indexes, and constraints.
It you run "sp_help tip" in SQL Server Management Studio, you will see the result as shown in
this picture:

 How To Generate CREATE TABLE Script on an Existing Table?


 If you want to know how an existing table was created, you can use SQL Server Management
Studio to automatically generate a "CREATE TABLE" script The following tutorial shows you how
to do this:
 1. Run SQL Server Management Studio and connect to SQL server.
 2. On the Object Explorer window, follow the object tree: Databases > FyiCenterData > Tables >
dbo.tip.
 3. Click right mouse button on dbo.tip. The context menu shows up.
 4. Select "Script Table as" > "CREATE to" > "New Query Editor Window". The following script will
be displayed:
 USE [FyiCenterData]
 GO
 /****** Object: Table [dbo].[tip]
 Script Date: 05/19/2007 21:34:19 ******/
 SET ANSI_NULLS ON
 GO
 SET QUOTED_IDENTIFIER ON
 GO
 SET ANSI_PADDING ON
 GO
 CREATE TABLE [dbo].[tip](
 [id] [int] NOT NULL,
 [subject] [varchar](80)
 COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [description] [varchar](256)
 COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [create_date] [datetime] NULL,
 PRIMARY KEY CLUSTERED (
 [id] ASC
 )WITH (PAD_INDEX = OFF,
 IGNORE_DUP_KEY = OFF) ON [PRIMARY]
 ) ON [PRIMARY]
 GO
 SET ANSI_PADDING OFF
 How to create new tables with "SELECT ... INTO" statements?
 Let's say you have a table with many data rows, now you want to create a backup copy of this
table of all rows or a subset of them, you can use the "SELECT ... INTO" statement. The tutorial
script below gives you a good example:
 INSERT INTO tip VALUES (1, 'Learn SQL',
 'Visit dev.fyicenter.com','2006-07-01')
 GO

 SELECT * INTO tipBackup FROM tip
 GO
 (1 rows affected)

 SELECT * FROM tipBackup
 GO
 id subject description create_date
 1 Learn SQL Visit dev.fyicenter.com 2006-07-01

 sp_columns tipBackup
 GO
 TABLE_OWNER TABLE_NAME COLUMN_TABLE TYPE_NAME ...
 dbo tipBackup id int ...
 dbo tipBackup subject varchar ...
 dbo tipBackup description varchar ...
 dbo tipBackup create_date datetime ...
 As you can see, the "SELECT ... INTO" statement created a table called "tipBackup" using the
same column definitions as the "tip" table and copied all data rows into "tipBackup".
 How To Add a New Column to an Existing Table with "ALTER TABLE ... ADD"?
 If you have an existing table with existing data rows, and want to add a new column to that table,
you can use the "ALTER TABLE ... ADD" statement. The tutorial script below shows you a good
example:
 ALTER TABLE tip ADD author VARCHAR(40)
 GO

 sp_columns tip
 GO
 TABLE_OWNER TABLE_NAME COLUMN_TABLE TYPE_NAME ...
 dbo tip id int ...
 dbo tip subject varchar ...
 dbo tip description varchar ...
 dbo tip create_date datetime ...
 dbo tip author datetime ...

 SELECT * FROM tip
 GO
 id subject description create_date author
 1 Learn SQL Visit dev.fyicenter.com 2006-07-01 NULL
 This SQL script added a new column called "author" to the "tip" table. NULL values were added
to this column on all existing data rows.
 How To Delete an Existing Column in a Table with "ALTER TABLE ... DROP COLUMN"?
 If you have an existing column in a table and you do not need that column any more, you can
delete it with "ALTER TABLE ... DROP COLUMN" statement. Here is a tutorial script to delete an
existing column:
 ALTER TABLE tip DROP COLUMN create_date
 GO

 SELECT * FROM tip
 GO
 id subject description author
 1 Learn SQL Visit dev.fyicenter.com NULL
 As you can see, the column "create_date" is gone.
 How to rename an existing column with the "sp_rename" stored procedure?
 If you have an existing column in a table and you want to change the column name, you can use
the "sp_rename ... 'COLUMN'" stored procedure. "sp_rename" allows you to change names of
COLUMN, DATABASE, INDEX, USERDATATYPE, and OBJECT. The tutorial example below
shows you how to rename a column:
 USE master
 GO

 sp_rename 'tip.subject', 'title', 'COLUMN'
 GO
 Msg 15248, Level 11, State 1, Procedure sp_rename, Line 213
 Either the parameter @objname is ambiguous or the claimed
 @objtype (COLUMN) is wrong.

 USE FyiCenterData
 GO

 sp_rename 'tip.subject', 'title', 'COLUMN'
 GO
 Caution: Changing any part of an object name could break
 scripts and stored procedures.

 SELECT id, title, description, author FROM tip
 GO
 id title description author
 1 Learn SQL Visit dev.fyicenter.com NULL
 You are getting the first error because 'FyiCenterData' is not the current database.
 How to rename an existing column with SQL Server Management Studio?
 If you are using SQL Server Management Studio, you can rename almost any data objects
through the Object Explorer window. The tutorial example below shows you how to rename a
column:
 1. Run SQL Server Management Studio and connect to SQL server.
 2. On the Object Explorer window, follow the object tree: Databases > FyiCenterData > Tables >
dbo.tip > Columns > title.
 3. Click right mouse button on "title". The context menu shows up.
 4. Select "Rename", type "subject" over "title", and press Enter key. The column name will be
changed.
 How to change the data type of an existing column with "ALTER TABLE" statements?
 Sometimes, you may need to change the data type of an existing column. For example, you want
increase the string length of a column. You can use the "ALTER TABLE ... ALTER COLUMN"
statements in the following syntax:
 ALTER TABLE table_name ALTER COLUMN column_name new_type
 Here is a good example of change column data types:
 -- Can not make a string column shorter
 ALTER TABLE tip ALTER COLUMN subject VARCHAR(10)
 GO
 Msg 8152, Level 16, State 14, Line 1
 String or binary data would be truncated.
 The statement has been terminated.

 -- Can make a string column longer
 ALTER TABLE tip ALTER COLUMN subject VARCHAR(100)
 GO
 Command(s) completed successfully.

 -- Can not change string to numeric
 ALTER TABLE tip ALTER COLUMN subject NUMBER
 GO
 Msg 8114, Level 16, State 5, Line 1
 Error converting data type varchar to numeric.
 The statement has been terminated.
 As you can see, the new date type must be compatible with the old data type in order for the
"ALTER TABLE ... ALTER COLUMN" statement to work
 How to rename an existing table with the "sp_rename" stored procedure?
 If you have an existing table and you want to change the table name, you can use the
"sp_rename ... 'OBJECT'" stored procedure. "sp_rename" allows you to change names of
COLUMN, DATABASE, INDEX, USERDATATYPE, and OBJECT (including tables). The tutorial
example below shows you how to rename a table:
 sp_rename 'tip', 'faq', 'OBJECT'
 GO
 Caution: Changing any part of an object name could break
 scripts and stored procedures.

 SELECT name, type_desc, create_date FROM sys.tables
 GO
 name type_desc create_date
 faq USER_TABLE 2007-05-19 23:05:43.700
 tipBackup USER_TABLE 2007-05-19 23:25:23.357
 You can also rename a table with on the Object Explorer window of SQL Server Management
Studio. See tutorials on rename table columns.
 How To Drop an Existing Table with "DROP TABLE" Statements?
 If you want to delete an existing table and its data rows, you can use the "DROP TABLE"
statement as shown in the tutorial script below:
 SELECT * FROM tipBackup
 GO
 id subject description create_date
 1 Learn SQL Visit dev.fyicenter.com 2006-07-01

 DROP TABLE tipBackup
 GO

 SELECT * FROM tipBackup
 GO
 Msg 208, Level 16, State 1, Line 1
 Invalid object name 'tipBackup'.
 Be careful, when you use the "DROP TABLE" statement. All data rows are gone too.

What Are DML (Data Manipulation Language) Statements?

DML (Data Manipulation Language) statements are statements to change data values in database
tables. The are 3 primary DML statements:
 INSERT - Inserting new rows into database tables. For example "INSERT INTO fyi_links
VALUES (101, 'dev.fyicenter.com', NULL, 0, '2006-04-30')" inserts a single new row in the
fyi_links table.
 UPDATE - Updating existing rows in database tables .
 DELETE - Deleting existing rows from database tables.

(Continued on next topic...)

How To Create a Testing Table with Test Data?

If you want to practice DML statements, like INSERT, UPDATE and DELETE statements, you should
create a testing table. The tutorial exercise shows you a good example:
CREATE TABLE fyi_links (id INTEGER PRIMARY KEY,
url VARCHAR(80) NOT NULL,
notes VARCHAR(1024),
counts INT,
created DATETIME NOT NULL DEFAULT(getdate()))
GO

SELECT c.column_id as seq, c.name, x.name as type,


c.max_length, c.is_nullable
FROM sys.columns c, sys.tables t, sys.systypes x
WHERE c.object_id = t.object_id
AND c.system_type_id = x.xtype
AND t.name = 'fyi_links'
ORDER BY c.column_id
GO
seq name type max_length is_nullable
1 id int 4 0
2 url varchar 80 0
3 notes varchar 1024 1
4 counts int 4 1
5 created datetime 8 0

You should keep this table to practice other tutorial exercises presented in this collection.

How To Insert a New Row into a Table with "INSERT INTO" Statements?

To insert a new row into a table, you can use the INSERT INTO statement with values specified for all
columns as in the following syntax:
INSERT INTO table_name VALUES (list_of_values_of_all columns)

Note that the list of values of all columns must be specified in the same order as how columns are
defined in the CREATE TABLE statement. The following tutorial example inserts a row into "fyi_links":
INSERT INTO fyi_links VALUES (101,
'dev.fyicenter.com',
NULL,
0,
'2006-04-30')
GO
(1 row(s) affected)

SELECT * FROM fyi_links


GO
id url notes counts created
101 dev.fyicenter.com NULL 0 2006-04-30

The values are stored in the new record nicely.

How To Use Column Default Values in INSERT Statements?

If a column is defined with a default value in a table, you can use the key word DEFAULT in the
INSERT statement to take the default value for that column. The following tutorial exercise gives a
good example:
INSERT INTO fyi_links VALUES (102,
'dba.fyicenter.com',
NULL,
0,
DEFAULT)
GO
(1 row(s) affected)

SELECT * FROM fyi_links


GO
id url notes counts created
101 dev.fyicenter.com NULL 0 2006-04-30
102 dba.fyicenter.com NULL 0 2007-05-19

The default value, getdate(), is used for "created" column, which gives the current date

How to provide column names in INSERT Statements?

If you don't want to specify values for columns that have default values, or you want to specify values
to columns in an order different than how they are defined, you can provide a column list in the
INSERT statement. If a column is omitted in the column, SQL Server applies 3 rules:
 If default value is defined for the column, that default value will be used.
 If no default value is defined for the column and NULL is allowed, NULL will be used.
 If no default value is defined for the column and NULL is not allowed, SQL Server will reject the
insert statement with an error.

The following tutorial exercise gives you some good examples:


INSERT INTO fyi_links (url, id)
VALUES ('sqa.fyicenter.com', 103)
GO
(1 row(s) affected)

INSERT INTO fyi_links (id) VALUES (110)


GO
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'url',
table 'FyiCenterData.dbo.fyi_links'; column does
not allow nulls. INSERT fails.
The statement has been terminated.

SELECT * FROM fyi_links


GO
id url notes counts created
101 dev.fyicenter.com NULL 0 2006-04-30
102 dba.fyicenter.com NULL 0 2007-05-19
103 dba.fyicenter.com NULL NULL 2007-05-19

The first INSERT statement shows that: the order of the columns is reversed; the default value is
taken for the un-specified column "created"; the NULL value is taken for the un-specified column
"counts", since is has no default value defined and null is allowed.

The second INSERT statement shows the error you get for the un-specified column "url", because it
has no default value, and null is not allowed.
What Happens If You Insert a Duplicate Key for the Primary Key Column?

If your table has a primary key column, and you are trying to insert a new row with duplicate key value
on the primary key column, you will get an error. The reason is simple - Primary key column does not
allow duplicate values. The following tutorial exercise gives you a good example:
SELECT * FROM fyi_links
INSERT INTO fyi_links VALUES (101,
'sql.fyicenter.com',
NULL,
0,
'2006-04-30')
GO
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint
'PK__fyi_links__03317E3D'. Cannot insert duplicate
key in object 'dbo.fyi_links'.
The statement has been terminated.

You are getting this error, because value "101" has already been used by an existing row.

How To Insert Multiple Rows with One INSERT Statement?

If you want to insert multiple rows with a single INSERT statement, you can use a subquery instead of
the VALUES clause. Rows returned from the subquery will be inserted the target table. The following
tutorial exercise gives you a good example:
INSERT INTO fyi_links SELECT id+500, REVERSE(url),
notes, counts, created FROM fyi_links
GO
(3 row(s) affected)

SELECT * FROM fyi_links


GO
id url notes counts created
101 dev.fyicenter.com NULL 0 2006-04-30
102 dba.fyicenter.com NULL 0 2007-05-19
103 sqa.fyicenter.com NULL NULL 2007-05-19
601 moc.retneciyf.ved NULL 0 2006-04-30
602 moc.retneciyf.abd NULL 0 2007-05-19
603 moc.retneciyf.aqs NULL NULL 2007-05-19

As you can see, "INSERT INTO ... SELECT ..." is powerful statement. you can use it build up data in
tables quickly.

How To Update Values in a Table with UPDATE Statements?

If you want to update some values in one row or multiple rows in a table, you can use the UPDATE
statement. The tutorial script below shows a good example:
SELECT * FROM fyi_links WHERE id = 101
GO
id url notes counts created
101 dev.fyicenter.com NULL 0 2006-04-30

UPDATE fyi_links SET counts = 999, notes = 'Good.'


WHERE id = 101;
GO
(1 row(s) affected)

SELECT * FROM fyi_links WHERE id = 101


GO
id url notes counts created
101 dev.fyicenter.com Good. 999 2006-04-30

As you can see, the SET clause takes column and value pairs to provide new values, while the
WHERE clause defines which row to apply the update

How To Update Multiple Rows with One UPDATE Statement?

If the WHERE clause in an UPDATE statement matches multiple rows, the SET clause will be applied
to all matched rows. This rule allows you to update values on multiple rows in a single UPDATE
statement. Here is a good example:
SELECT * FROM fyi_links WHERE id >= 500
GO
id url notes counts created
601 moc.retneciyf.ved NULL 0 2006-04-30
602 moc.retneciyf.abd NULL 0 2007-05-19
603 moc.retneciyf.aqs NULL NULL 2007-05-19

SELECT * FROM fyi_links


UPDATE fyi_links SET counts = 9, notes = 'Wrong'
WHERE id >= 500
(3 row(s) affected)

SELECT * FROM fyi_links WHERE id >= 500


GO
id url notes counts created
601 moc.retneciyf.ved Wrong 9 2006-04-30
602 moc.retneciyf.abd Wrong 9 2007-05-19
603 moc.retneciyf.aqs Wrong 9 2007-05-19

The UPDATE statement updated 3 rows with the same new values.

How to use old values to define new values in UPDATE statements?


If a row matches the WHERE clause in a UPDATE statement, existing values in this row can be used
in expressions to provide new values in the SET clause. Existing values are represented by column
names in the expressions. The tutorial exercise below shows you a good example:
SELECT * FROM fyi_links WHERE id >= 500
GO
id url notes counts created
601 moc.retneciyf.ved Wrong 9 2006-04-30
602 moc.retneciyf.abd Wrong 9 2007-05-21
603 moc.retneciyf.aqs Wrong 9 2007-05-23

UPDATE fyi_links SET id = id+200, counts = id*2


WHERE id >= 500
GO
(3 row(s) affected)

SELECT * FROM fyi_links WHERE id >= 500


GO
id url notes counts created
801 moc.retneciyf.ved Wrong 1202 2006-04-30
802 moc.retneciyf.abd Wrong 1204 2007-05-19
803 moc.retneciyf.aqs Wrong 1206 2007-05-19

This statement increased values in the id column by 200. It also updated the counts column with the
newly increased id value.

Is the Order of Columns in the SET Clause Important?

The answer is NO. The order of columns in the SET clause of the UPDATE statement is NOT
important. You probably already noticed from the previous tutorial. There is a BIG DIFFERENCE
among SQL Server, MySQL and Oracle on update multiple columns with previous values:
 SQL Server provides you the existing values from the database on columns names used in new
value expressions. So the order of columns in the SET clause is NOT important
 MySQL provides you the updated values on columns names used in new value expressions. So
the order of columns in the SET clause is important.
 Oracle provides you the existing values from the database on columns names used in new value
expressions. So the order of columns in the SET clause is NOT important

Here is a good tutorial exercise:


SELECT * FROM fyi_links
-- Check the old values
SELECT * FROM fyi_links WHERE url = 'dev.fyicenter.com'
GO
id url notes counts created
101 dev.fyicenter.com Good. 999 2006-04-30

-- Update "id" before "counts"


UPDATE fyi_links SET id = id+200, counts = id*2
WHERE url = 'dev.fyicenter.com'
GO
(1 row(s) affected)

-- Check the new values


SELECT * FROM fyi_links WHERE url = 'dev.fyicenter.com'
GO
id url notes counts created
301 dev.fyicenter.com Good. 202 2006-04-30

-- Reset to old values


UPDATE fyi_links SET id = 101, counts = 999
WHERE url = 'dev.fyicenter.com'
(1 row(s) affected)

Notice that the "id" in the "counts" new value expression is taking the old value of the "id" column, not
the updated value, even the "id" column is updated before the "counts" column.

Now try this on a MySQL server, you will get different result.

How To Use Values from Other Tables in UPDATE Statements?

If you want to update values in one table with values from another table, you can use a subquery as
an expression in the SET clause. The subquery should return only one row for each row in the update
table that matches the WHERE clause. The tutorial exercise below shows you a good example:
-- Create another table
CREATE TABLE fyi_rates (id INTEGER,
comment VARCHAR(16))
Go

-- Insert some rows in the new table


INSERT INTO fyi_rates VALUES (101, 'The best')
Go
INSERT INTO fyi_rates VALUES (102, 'Well done')
GO
INSERT INTO fyi_rates VALUES (103, 'Thumbs up')
Go

-- Update fyi_links with values from fyi_rates


UPDATE fyi_links SET notes = (
SELECT comment FROM fyi_rates
WHERE fyi_rates.id = fyi_links.id
)
WHERE id > 0 AND id < 110
GO
(3 row(s) affected)

-- View the updated values


SELECT * FROM fyi_links
WHERE id > 0 AND id < 110
GO
id url notes counts created
101 dev.fyicenter.com The best 999 2006-04-30
102 dba.fyicenter.com Well done 0 2007-05-19
103 sqa.fyicenter.com Thumbs up NULL 2007-05-19

Note that if column names are confusing between the inner table and the outer table, you need to
prefix column names with table names, like "fyi_rates.id = fyi_links.id".

What Happens If the UPDATE Subquery Returns No Rows?

If you use a subquery to assign new values in the SET clause in an UPDATE statement, and the
subquery returns no rows for an outer row, SQL Server will provide a NULL value to the SET clause.
The tutorial exercise below shows you a good example:
-- insert a new row
INSERT INTO fyi_links (id, url, notes)
VALUES (0, 'www.fyicenter.com', 'Number one')
GO
(1 row(s) affected)

-- view old values


SELECT * FROM fyi_links WHERE id = 0
GO
id url notes counts created
0 www.fyicenter.com Number one NULL 2007-05-23

-- make sure there is no matching row in fyi_rates


SELECT * FROM fyi_rates WHERE id = 0
GO
0 rows

-- update a subquery returning no rows


UPDATE fyi_links SET notes = (
SELECT comment FROM fyi_rates
WHERE fyi_rates.id = fyi_links.id
)
WHERE id = 0
(1 row(s) affected)

-- view new values


SELECT * FROM fyi_links WHERE id = 0
GO
id url notes counts created
0 www.fyicenter.com NULL NULL 2007-05-23

Column "notes" gets updated with NULL if there is no return rows in the subquery

What Happens If the UPDATE Subquery Returns Multiple Rows?

If a subquery is used in a UPDATE statement, it must return exactly one row for each row in the
update table that matches the WHERE clause. If it returns multiple rows, SQL Server will give you an
error message. To test this out, you can try the following tutorial exercise:
-- insert two rows to fyi_rates
INSERT INTO fyi_rates VALUES (0, 'Number 1')
GO
INSERT INTO fyi_rates VALUES (0, 'Number 2')
GO

-- make sure there are 2 match rows


SELECT * FROM fyi_rates WHERE id = 0
GO
id comment
0 Number 1
0 Number 2

-- update with subquery that returns 2 rows


UPDATE fyi_links SET notes = (
SELECT comment FROM fyi_rates
WHERE fyi_rates.id = fyi_links.id
)
WHERE id = 0
GO
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted
when the subquery follows =, !=, <, <= , >, >= or when
the subquery is used as an expression.
The statement has been terminated.

It is clear that we are using subquery as an expression, and it must return 0 or 1 row. Otherwise, we
will get an error.
How To Delete an Existing Row with DELETE Statements?

If you want to delete an existing row from a table, you can use the DELETE statement with a WHERE
clause to identify that row. Here is good sample of DELETE statements:
-- insert a row for this test
INSERT INTO fyi_links (url, id)
VALUES ('www.myspace.com', 301)
GO
(1 row(s) affected)

-- view the inserted row


SELECT id, url, notes, counts FROM fyi_links
WHERE id = 301
GO
id url notes counts
301 www.myspace.com NULL NULL

-- delete one row


DELETE FROM fyi_links WHERE id = 301
GO
(1 row(s) affected)

-- try to view the deleted row


SELECT id, url, notes, counts FROM fyi_links
WHERE id = 301
no rows

Row with id of 301 is truly deleted.

How To Delete Multiple Rows with One DELETE Statement?

You can delete multiple rows from a table in the same way as deleting a single row, except that the
WHERE clause will match multiple rows. The tutorial exercise below deletes 3 rows from the fyi_links
table:
-- view rows to be deleted
SELECT id, url, notes, counts FROM fyi_links
WHERE id > 300
GO
id url notes counts
801 moc.retneciyf.ved Wrong 1202
802 moc.retneciyf.abd Wrong 1204
803 moc.retneciyf.aqs Wrong 1206

-- delete multiple rows


DELETE FROM fyi_links WHERE id > 300
GO
(3 row(s) affected)
-- try to view the deleted row
SELECT id, url, notes, counts FROM fyi_links
WHERE id > 300
GO
no rows

How To Delete All Rows with DELETE Statements?

If you want to delete all rows from a table, you have two options:
 Use the DELETE statement with no WHERE clause.
 Use the TRUNCATE TABLE statement.

Here is an example of deleting all rows with a DELETE statement:


SELECT COUNT(*) FROM fyi_links
GO
4

DELETE FROM fyi_links


GO
(4 row(s) affected)

SELECT COUNT(*) FROM fyi_links


GO
0

How To Delete All Rows with TRUNCATE TABLE Statement?

If you want to delete all rows from a table, you have two options:
 Use the DELETE statement with no WHERE clause.
 Use the TRUNCATE TABLE statement.

The TRUNCATE statement is more efficient the DELETE statement. The tutorial exercise shows you
a good example of TRUNCATE statement:
SELECT COUNT(*) FROM fyi_rates
GO
5

TRUNCATE TABLE fyi_rates


GO

SELECT COUNT(*) FROM fyi_rates


GO
0

You might also like