You are on page 1of 16

Introduction To create a database in SQL, use the following formula:

CREATE DATABASE DatabaseName

Here is an example:
CREATE DATABASE BethesdaCarRental;

If you want the name of the database to be in different words, include them in square brackets. Here is an example:
CREATE DATABASE [Bethesda Car Rental];

If you want the name of the database to be in different words, include them in square brackets. To start from a sample code, open an empty Query window and display the Template Explorer. From the Template Explorer, expand Database. Drag Create Database and drop it in the Query window:
-- ============================================= -- Create database template -- ============================================= USE master GO -- Drop the database if it already exists IF EXISTS ( SELECT name FROM sys.databases WHERE name = N'<Database_Name, sysname, Database_Name>' ) CREATE DATABASE <Database_Name, sysname, Database_Name>

Introduction To delete a database, you use the DROP DATABASE expression followed by the name of the database. The formula used is:
DROP DATABASE DatabaseName;

Here is an example:

DROP DATABASE RealEstate1; GO

To start from a sample code, open an empty Query window and display the Template Explorer. From the Template Explorer, expand Database. Drag the Drop Database node and drop it in the Query window:
-- ========================= -- Drop Database Template -- ========================= USE master GO IF EXISTS ( SELECT name FROM sys.databases WHERE name = N'<Database_Name, sysname, Database_Name>' ) DROP DATABASE <Database_Name, sysname, Database_Name> GO

To delete a database in SQL Server Management Studio, in the Object Explorer, expand the Databases node, right-click the undesired database, and click Delete. A dialog box would prompt you to confirm your intention. If you still want to delete the database, you can click OK. If you change your mind, you can click Cancel.

Renaming a Database Description To change the name of a database, Transact-SQL provides sp_renamedb. The formula used would be:
EXEC sp_renamedb 'ExistingName', 'NewName'

The EXEC sp_renamedb expression is required. The ExistingName factor is the name of the database that you want to rename. The NewName factor is the name you want the database to have after renaming it. Here is an example of renaming a database:
EXEC sp_renamedb 'RentalCars', 'BethesdaCarRental GO

Transact-SQL: Creating a Table Introduction To create a table, you can follow this formula:
CREATE TABLE Country(Column1, Column2, Column3)

or:
CREATE TABLE Country( Column1, Column2, Column3);

Each column is created as:


ColumnName DataType Options

Here is an example:
CREATE TABLE Customers ( DrvLicNbr nvarchar(32), DateIssued DATE, DateExpired date, FullName nvarchar(50), Address NVARCHAR(120), City NvarChar(40), State NVarChar(50), PostalCode nvarchar(20), HomePhone nvarchar(20), OrganDonor BIT); GO

To start from a sample code, open an empty Query window and display the Template Explorer. From the Template Explorer, expand Table. Drag Create Table and drop it in the Query window:
-- ========================================= -- Create table template -- ========================================= USE <database, sysname, AdventureWorks> GO IF OBJECT_ID('<schema_name, sysname, dbo>.<table_name, sysname, sample_table>', 'U') IS NOT NULL DROP TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> GO CREATE TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> ( <columns_in_primary_key, , c1> <column1_datatype, , int> <column1_nullability,, NOT NULL>, <column2_name, sysname, c2> <column2_datatype, , char(10)>

<column2_nullability,, NULL>, <column3_name, sysname, c3> <column3_datatype, , datetime> <column3_nullability,, NULL>, CONSTRAINT <contraint_name, sysname, PK_sample_table> PRIMARY KEY (<columns_in_primary_key, , c1>) ) GO

You can then modify/customize this code.

eleting a Table Introduction To delete a table using SQL, use the following formula:
DROP TABLE TableName

The DROP TABLE expression is required and it is followed by the name of the undesired table. Here is an example:
DROP TABLE Students; GO

Renaming a Table Introduction To rename a table using code, execute the sp_rename stored procedure using the following formula:
sp_rename ExistingTableName, TableNewName;

Here is an example:
sp_rename 'StaffMembers', 'Employees'; GO

In this case, the interpreter would look for a table named StaffMembers in the current or selected database. If it finds it, it would rename it Employees. If the table doesn't exist, you would receive an error.

Creating a View Introduction The formula to programmatically create a view is:


CREATE VIEW ViewName AS SELECT Statement

Here is an example:
USE Exercise; GO CREATE SCHEMA Personnel; GO CREATE TABLE Personnel.Employees(EmplNbr nchar(10), FirstName nvarchar(20), LastName nvarchar(20), Salary money, FullTime bit); GO INSERT INTO Personnel.Employees VALUES(N'29730', N'Philippe', N'Addy', 20.05, 1), (N'28084', N'Joan', N'Shepherd', 12.72, 0), (N'79272', N'Joshua', N'Anderson', 18.26, 0), (N'22803', N'Gregory', N'Swanson', 15.95, 0), (N'83084', N'Josephine', N'Anderson', 20.02, 1); GO CREATE VIEW Personnel.StaffMembers AS SELECT FirstName, LastName, Salary FROM Personnel.Employees; GO

Here is an example that includes a condition:


CREATE VIEW Personnel.GoodSalaries AS SELECT FirstName, LastName, Salary FROM Personnel.Employees WHERE Salary >= 16.00; GO

Here is an example of a view that uses two tables:


CREATE VIEW People.ListOfMen AS SELECT People.Genders.Gender, People.Persons.FirstName, People.Persons.LastName FROM People.Genders INNER JOIN People.Persons

ON People.Genders.GenderID = People.Persons.GenderID; GO

Here is an example of a view that uses two tables:


CREATE VIEW People.ListOfMen AS SELECT People.Genders.Gender, People.Persons.FirstName, People.Persons.LastName FROM People.Genders INNER JOIN People.Persons ON People.Genders.GenderID = People.Persons.GenderID WHERE (People.Genders.Gender = N'Male'); GO

Here is an example of a view with alias names:


CREATE VIEW dbo.MenAndWomen([First Name], [Last Name], Gender) AS SELECT dbo.Persons.FirstName, dbo.Persons.LastName, dbo.Genders.Gender FROM dbo.Genders INNER JOIN dbo.Persons ON dbo.Genders.GenderID = dbo.Persons.GenderID; GO

Views and Functions To create more complex or advanced views, you can involve functions. As always, probably the easiest functions to use are those built-in. If there is no built-in function that performs the operation you want, you can create your own. Here is an example:
CREATE FUNCTION Registration.GetFullName ( @FName nvarchar(20), @LName nvarchar(20) ) RETURNS nvarchar(41) AS BEGIN RETURN @LName + N', ' + @FName; END GO

Once you have a function you want to use, you can call it in the body of your view as you judge it necessary. Here is an example:
CREATE VIEW Registration.StaffMembers AS SELECT Registration.GetFullName(FirstName, LastName) AS [Full Name] FROM Registration.Teachers; GO

SELECT * FROM Registration.StaffMembers; GO

This would produce:

Altering a View Introduction The basic formula to programmatically modify a view is:
ALTER VIEW ViewName AS SELECT Statement

Here is an example:
ALTER VIEW dbo.ListOfMen AS SELECT dbo.Persons.FirstName, dbo.Persons.LastName FROM dbo.Genders INNER JOIN dbo.Persons ON dbo.Genders.GenderID = dbo.Persons.GenderID WHERE (dbo.Genders.Gender = N'Male');

Dropping a View Introduction The formula to programmatically delete a view is:


DROP VIEW ViewName

Here is an example
DROP VIEW Personnel.StaffMembers; GO

Data Entry With a View Introduction Imagine you have a view as follows:
CREATE VIEW Personnel.EmployeesNames AS SELECT FirstName, LastName, LastName + N', ' + FirstName AS FullName FROM Persons; GO

Here is an example of creating a record using a view:


INSERT INTO Personnel.EmployeesNames(FirstName, LastName) VALUES(N'Peter', N'Justice');

Primary Keys Introduction

To create a primary column using SQL, use the PRIMARY KEY keyword. Here is an example:
CREATE TABLE Persons ( PersonID int identity(1,1) PRIMARY KEY NOT NULL, FirstName nvarchar(20), LastName nvarchar(20) NOT NULL );

A Constraint on the Primary Key You can also create a primary key as a constraint. The formula to use is:
CONSTRAINT PrimaryKeyName PRIMARY KEY(ColumnName)

Here is an example:
CREATE TABLE Persons ( PersonID int identity(1,1) NOT NULL, FirstName nvarchar(20), LastName nvarchar(20) NOT NULL, CONSTRAINT PrimKeyPeople PRIMARY KEY(PersonID) );

By convention or tradition, the name of the primary starts with PK_ followed by the name of the table. Here is an example:
USE Exercise2; GO CREATE TABLE Persons ( PersonID int identity(1,1) NOT NULL, FirstName nvarchar(20), LastName nvarchar(20) NOT NULL, CONSTRAINT PK_Persons PRIMARY KEY(PersonID) ); GO

Foreign Keys Introduction To create a foreign key in the SQL, the basic formula to use is:
FOREIGN KEY REFERENCES ParentTableName(ForeignKeyCcolumn)

Here is an example:

CREATE TABLE Persons ( PersonID int identity(1,1) PRIMARY KEY NOT NULL, FirstName nvarchar(20), LastName nvarchar(20) NOT NULL, GenderID int NULL FOREIGN KEY REFERENCES Genders(GenderID) );

A Constraint on a Foreign Key To create a foreign key as a constraint, use the CONSTRAINT keyword followed by the desired name and continue the rest as we saw above. Her is an example:
CREATE TABLE Persons ( PersonID int identity(1,1) PRIMARY KEY NOT NULL, FirstName nvarchar(20), LastName nvarchar(20) NOT NULL, GenderID int NULL CONSTRAINT FKGenders FOREIGN KEY REFERENCES Genders(GenderID) );

Transact-SQL: Adding a Column to a Table Introduction To add a new column to a table, follow this formula:
ALTER TABLE TableName ADD ColumnName Properties

Here is an example:
ALTER TABLE StaffMembers ADD Address varchar(100) NULL GO

When this code is executed, a new column named Address, of type varchar, with a limit of 100 characters, and t entries, would be added to the table named StaffMembers.

To use sample code, first display an empty query window and display the Templates Explorer. Expand the Table Table, drag Add Column and drop it in the query window. Delete the undesired sections of code and keep only th with adding a column. Here is an example:
--========================================================================== -- Add column template --- This template creates a table, then it adds a new column to the table. --==========================================================================

USE <database, sysname, AdventureWorks> GO -- Add a new column to the table ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> ADD <new_column_name, sysname, column3> <new_column_datatype,, datetime> <new_column_nullability,, NULL> GO

An Identity Column Description An identity column is one whose value is automatically created by the database engine when a new record is added. This makes sure that each record has a unique value for that field. To visually create an identity column, display the table in Design View. In the top section, specify the name of the column. Set its data type to an integer-based type. Usually, the data type used is int. In the bottom section, click and expand the Identity Specification property. The first action you should take is to set its (Is Identity) property from No to Yes. Once you have set the value of the (Is Identity) property to Yes, the first time the user performs data entry, the value of the first record would be set to 1. This characteristic is controlled by the Identity Seed property. If you want the count to start to a value other than 1, specify it on this property. After the (Is Identity) property has been set to Yes, the SQL interpreter would increment the value of each new record by 1, which is the default. This means that the first record would have a value of 1, the second would have a value of 2, and so on. This aspect is controlled by the Identity Increment property. If you want to increment by more than that, you can change the value of the Identity Increment property. To create an identity column in Transact-SQL, after the name and data type of the column, type identity followed by parentheses. Between the parentheses, enter the seed value, followed by a comma, followed by the increment value. Here is an example:
CREATE TABLE StoreItems( ItemID int IDENTITY(1, 1) NOT NULL, Category nvarchar(50), ItemName nvarchar(100) NOT NULL, Size nvarchar(20), UnitPrice money); GO

Transact-SQL: Deleting a Column Introduction To delete a column using code, first open or access an empty query window, and use the following formula:
ALTER TABLE TableName DROP COLUMN ColumnName

On the right side of the ALTER TABLE expression, type the name of the table. On the right side of the DROP expression, enter the name of the undesired column. Here is an example:
ALTER TABLE StaffMembers DROP COLUMN CurrentResidence; GO

When this code is executed, the interpreter will look for a column named CurrentResidence in a table named Staf current or selected database. If it finds that column, it will remove it from the table.

Microsoft SQL Server can also generate sample code you can use to delete a column from a table. Before doing t an empty query window and display the Templates Explorer. Expand the Table node. In the Table section, drag D drop it in the query window. Delete the undesired sections of code and keep only the part that deals with adding a an example:
--============================================ -- Drop column template --- This template creates a table, then it -- drops one of the columns of the table. --============================================ USE <database, sysname, AdventureWorks> GO -- Drop a column from the table ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, sample_table> DROP COLUMN <new_column_name, sysname, column3> GO

Transact-SQL: Renaming a Column Introduction To rename a column, first open an empty query window. In a query window, execute sp_rename using the following formula:
sp_rename 'TableName.ColumnName', 'NewColumnName', 'COLUMN'

The sp_rename factor and the 'COLUMN' string are required. The TableName factor is the name of the table that the column belongs to. The ColumnName is the current name of the column. The NewColumnName is the desired name you want to give to the column. Here is an example:
sp_rename 'StaffMembers.FullName', 'EmployeeName', 'COLUMN' GO

When this code is executed, the interpreter will look for a column named FullName in the StaffMembers table of the current or selected database. If it finds that column in the table, then it renames it EmployeeName.

CREATE TRIGGER (Transact-SQL) Creates a DML, DDL, or logon trigger. A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view. These triggers fire when any valid event is fired, regardless of whether or not any table rows are affected. DDL triggers execute in response to a variety of data definition language (DDL) events. These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP statements, and certain system stored procedures that perform DDL-like operations. Logon triggers fire in response to the LOGON event that is raised when a user sessions is being established. Triggers can be created directly from Transact-SQL statements or from methods of assemblies that are created in the Microsoft .NET Framework common language runtime (CLR) and uploaded to an instance of SQL Server. SQL Server allows for creating multiple triggers for any specific statement. Security Note Malicious code inside triggers can run under escalated privileges. For more information on how to mitigate this threat, see Managing Trigger Security. Transact-SQL Syntax Conventions Syntax
Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger) CREATE TRIGGER [ schema_name . ]trigger_name ON { table | view } [ WITH <dml_trigger_option> [ ,...n ] ] { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } [ WITH APPEND ]

[ NOT FOR REPLICATION ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > } <dml_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_name Trigger on a CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE STATISTICS statement (DDL Trigger) CREATE TRIGGER trigger_name ON { ALL SERVER | DATABASE } [ WITH <ddl_trigger_option> [ ,...n ] ] { FOR | AFTER } { event_type | event_group } [ ,...n ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME < method specifier > [ ; ] } <ddl_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_name Trigger on a LOGON event (Logon Trigger) CREATE TRIGGER trigger_name ON ALL SERVER [ WITH <logon_trigger_option> [ ,...n ] ] { FOR| AFTER } LOGON AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME < method specifier > ] } <logon_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_name

[ ;

A. Dropping an index
The following example deletes the index IX_ProductVendor_VendorID on the ProductVendor table. SQL
USE AdventureWorks2008R2; GO DROP INDEX IX_ProductVendor_BusinessEntityID

ON Purchasing.ProductVendor; GO

B. Dropping multiple indexes


The following example deletes two indexes in a single transaction. SQL
USE AdventureWorks2008R2; GO DROP INDEX IX_PurchaseOrderHeader_EmployeeID ON Purchasing.PurchaseOrderHeader, IX_Address_StateProvinceID ON Person.Address; GO

A. Dropping a table in the current database


The following example removes the ProductVendor1 table and its data and indexes from the current database.
DROP TABLE ProductVendor1 ;

B. Dropping a table in another database


The following example drops the SalesPerson2 table in the AdventureWorks2008R2 database. The example can be executed from any database on the server instance.
DROP TABLE AdventureWorks2008R2.dbo.SalesPerson2 ;

C. Dropping a temporary table


The following example creates a temporary table, tests for its existence, drops it, and tests again for its existence. SQL
USE AdventureWorks2008R2; GO CREATE TABLE #temptable (col1 int); GO INSERT INTO #temptable VALUES (10); GO SELECT * FROM #temptable; GO IF OBJECT_ID(N'tempdb..#temptable', N'U') IS NOT NULL DROP TABLE #temptable;

GO --Test the drop. SELECT * FROM #temptable;

TRUNCATE TABLE (Transact-SQL) Removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources. Transact-SQL Syntax Conventions Syntax
TRUNCATE TABLE [ { database_name .[ schema_name ] . | schema_name . } ] table_name [ ; ]

The following example removes all data from the JobCandidate table. SELECT statements are included before and after the TRUNCATE TABLE statement to compare results.
USE AdventureWorks2008R2; GO SELECT COUNT(*) AS BeforeTruncateCount FROM HumanResources.JobCandidate; GO TRUNCATE TABLE HumanResources.JobCandidate; GO SELECT COUNT(*) AS AfterTruncateCount FROM HumanResources.JobCandidate; GO