SQL SERVER noteS......ip notes....
FUNCTION
CREATE FUNCTION Addition()
RETURNS Decimal(6,3)
RETURNS Decimal(6,3)
BEGIN
END
RETURNS Decimal(6,3)
AS
BEGIN
END
RETURNS Decimal(6,3)
AS
BEGIN
RETURN Expression
END
RETURNS varchar(100)
AS
BEGIN
RETURN 'Doe, John'
END
RETURNS Decimal(8, 2)
AS
BEGIN
RETURN 880.44
END;
GO
RETURNS int
BEGIN
RETURN 1
END
RETURNS int
BEGIN
DECLARE @Number1 int
SET @Number1 = 588
RETURN @Number1 + 1450
END
RETURNS Decimal(6,2)
BEGIN
RETURN @Number1 + 1450
END
@Number2 Decimal(6,2))
RETURNS Decimal(6,2)
BEGIN
DECLARE @Result Decimal(6,2)
SET @Result = @Number1 + @Number2
RETURN @Result
END;
GO
@Nbr2 Decimal(6,2)
SET @Nbr1 = 4268.55
SET @Nbr2 =26.83
SELECT @Nbr1 As First,
@Nbr2 As Second,
Variables1.dbo.Addition(@Nbr1, @Nbr2) AS Result
DROP A FUnCTIOn
Create a view
AS
SELECT Statement
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
AS
SELECT FirstName, LastName, Salary
FROM Personnel.Employees
WHERE Salary >= 16.00;
GO
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
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
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
(
@FName nvarchar(20),
@LName nvarchar(20)
)
RETURNS nvarchar(41)
AS
BEGIN
RETURN @LName + N', ' + @FName;
END
GO
AS
SELECT Registration.GetFullName(FirstName, LastName) AS [Full Name]
FROM Registration.Teachers;
GO
SELECT * FROM Registration.StaffMembers;
GO
Alter vew
AS
SELECT Statement
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');
Drop view
GO
Data entry with a view
AS
SELECT FirstName,
LastName,
LastName + N', ' + FirstName AS FullName FROM Persons;
GO
VALUES(N'Peter', N'Justice');
Foreign key
(
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)
);
(
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)
);
ItemID int IDENTITY(1, 1) NOT NULL,
Category nvarchar(50),
ItemName nvarchar(100) NOT NULL,
Size nvarchar(20),
UnitPrice money);
GO
FOR LOGIN rkouma;
GO
USE Exercise1;
GO
GRANT CREATE FUNCTION
TO rkouma;
GO
GO
GRANT CREATE ANY DATABASE
TO operez;
GO
TO operez;
GO
TO pkatts, gdmonay;
GO
TO Login1, Login2, Login_n
TO rkouma;
GO
{ TO | FROM } <database_principal> [ ,...n ]
[ CASCADE ]
[ AS <database_principal> ]
<permission> ::= permission | ALL [ PRIVILEGES ]
<database_principal> ::= Database_user
| Database_role
| Application_role
| Database_user_mapped_to_Windows_User
| Database_user_mapped_to_Windows_Group
| Database_user_mapped_to_certificate
| Database_user_mapped_to_asymmetric_key
| Database_user_with_no_login
DENY CREATE ANY DATABASE
TO rkouma;
GO
*/
REVOKE CREATE ANY DATABASE
TO rkouma;
GO
TO rkouma;
GO
GRANT CREATE ANY DATABASE
TO rkouma;
GO
TO Login1, Login2, Login_n
WITH GRANT OPTION
<schema_name_clause> ::=
{
schema_name
| AUTHORIZATION owner_name
| schema_name AUTHORIZATION owner_name
}
<schema_element> ::=
{
table_definition | view_definition | grant_statement |
revoke_statement | deny_statement
}
2> GO
1>
(
FullName NVARCHAR(50),
Address NVARCHAR(80),
City NVARCHAR(40),
State NVARCHAR(40) DEFAULT N'NSW',
PostalCode NVARCHAR(4) DEFAULT N'2000',
Country NVARCHAR(20) DEFAULT N'Australia'
);
GO
(
EmployeeName nvarchar(50),
DateHired date default GETDATE(),
Address nvarchar(50),
City nvarchar(40),
State nchar(2) DEFAULT 'VA',
PostalCode NVARCHAR(4),
Country NVARCHAR(20)
);
GO
GO
ALTER TABLE Employees
ADD HomePhone nvarchar(20) default N'(000) 000-0000';
GO
(
CircleID int identity(1,1) NOT NULL,
Radius decimal(8, 3) NOT NULL,
Area AS Radius * Radius * PI()
);
GO
GO
INSERT INTO Circle(Radius) VALUES(8.15);
GO
INSERT INTO Circle(Radius) VALUES(122.57);
GO
*
(
FirstName varchar(20) NULL,
LastName varchar(20) NOT NULL,
Gender smallint
);
GO
CREATE FUNCTION Addition()
RETURNS Decimal(6,3)
After specifying the type of value that the function would return, you can create a body for the function. The body of a function starts with the BEGIN and ends with the END keywords. Here is an example:
CREATE FUNCTION Addition()RETURNS Decimal(6,3)
BEGIN
END
Optionally, you can type the AS keyword before the BEGIN keyword:
CREATE FUNCTION Addition()RETURNS Decimal(6,3)
AS
BEGIN
END
Between the BEGIN and END keywords, which is the section that represents the body of the function, you can define the assignment the function must perform. After performing this assignment, just before the END keyword, you must specify the value that the function returns. This is done by typing the RETURN keyword followed by an expression. A sample formula is:
CREATE FUNCTION Addition()RETURNS Decimal(6,3)
AS
BEGIN
RETURN Expression
END
Here is an example
CREATE FUNCTION GetFullName()RETURNS varchar(100)
AS
BEGIN
RETURN 'Doe, John'
END
Here is another example:
CREATE FUNCTION CalculateWeeklySalary()RETURNS Decimal(8, 2)
AS
BEGIN
RETURN 880.44
END;
GO
Function Calling |
After a function has been created, you can use the value it returns. Using a function is also referred to as calling it. To call a function, you must qualify its name. To do this, type the name of the database in which it was created, followed by the period operator, followed by dbo, followed by the period operator, followed by the name of the function, and its parentheses. The formula to use is:
DatabaseName.dbo.FunctionName()
Because a function returns a value, you can use that value as you see fit. For example, you can use either PRINT or SELECT to display the function's value in a query window. Here is an example that calls the above Addition() function:
PRINT Exercise.dbo.GetFullName();
As an alternative, to call a function, in the Object Explorer, right-click its name, position the mouse on Script Function As, SELECT To, and click New Query Editor Window.
Renaming a Function |
To rename a function, in the Object Explorer, right-click it and click Rename. Type the desired new name and press Enter.
Modifying a Function |
As mentioned already, in the body of the function, you define what the function is supposed to take care of. As a minimum, a function can return a simple number, typed on the right side of the RETURN keyword. Here is an example:
CREATE FUNCTION Addition()RETURNS int
BEGIN
RETURN 1
END
You can also declare new variables in the body of the function to help in carrying the assignment. A variable declared in the body of a function is referred to as a local variable. Once such a variable has been declared, it can be used like any other variable. Here is an example:
CREATE FUNCTION Addition()RETURNS int
BEGIN
DECLARE @Number1 int
SET @Number1 = 588
RETURN @Number1 + 1450
END
A Parameterized Function |
To create a function that takes a parameter, specify a name and the type of value of the parameter(s) in its parentheses. Here is an example:
CREATE FUNCTION Addition(@Number1 Decimal(6,2))
When a function takes a parameter, in the body of the function, you can use the parameter as if you knew its value, as long as you respect the type of that value. Here is an example:
CREATE FUNCTION Addition(@Number1 Decimal(6,2))RETURNS Decimal(6,2)
BEGIN
RETURN @Number1 + 1450
END
Calling a Parameterized Function |
When you call a function that takes one parameter, you must supply a value for that argument. To do this, type the value of the parameter in the parentheses of the function. Here is an example:
A Function With Various Arguments |
Instead of only one parameter, you can also create a function that takes more than one parameter. In this case, separate the arguments in the parentheses of the function with a comma. Here is an example:
CREATE FUNCTION Addition(@Number1 Decimal(6,2), @Number2 Decimal(6,2))
Once again, in the body of the function, you can use the parameters as if you already knew their value. You can also declare local variables and involve them with parameters as you see fit. Here is an example:
CREATE FUNCTION Addition(@Number1 Decimal(6,2),@Number2 Decimal(6,2))
RETURNS Decimal(6,2)
BEGIN
DECLARE @Result Decimal(6,2)
SET @Result = @Number1 + @Number2
RETURN @Result
END;
GO
When calling a function that takes more than one parameter, in the parentheses of the function, provide a value for each parameter, in the exact order they appear in the parentheses of the function. Here is an example:
PRINT Variables1.dbo.Addition(1450, 228);
You can also pass the names of already declared and initialized variables. Here is an example that calls the above function:
DECLARE @Nbr1 Decimal(6,2),@Nbr2 Decimal(6,2)
SET @Nbr1 = 4268.55
SET @Nbr2 =26.83
SELECT @Nbr1 As First,
@Nbr2 As Second,
Variables1.dbo.Addition(@Nbr1, @Nbr2) AS Result
This would produce:
DROP A FUnCTIOn
Introduction |
To delete a function in the Object Explorer, right-click it and click Delete.
To programmatically delete a function:
|
Create a view
Introduction |
The formula to programmatically create a view is:
CREATE VIEW ViewNameAS
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.GoodSalariesAS
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.ListOfMenAS
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.ListOfMenAS
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.StaffMembersAS
SELECT Registration.GetFullName(FirstName, LastName) AS [Full Name]
FROM Registration.Teachers;
GO
SELECT * FROM Registration.StaffMembers;
GO
This would produce:
Alter vew
Introduction |
The basic formula to programmatically modify a view is:
ALTER VIEW ViewNameAS
SELECT Statement
Here is an example:
ALTER VIEW dbo.ListOfMenAS
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');
Drop 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.EmployeesNamesAS
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');
Foreign key
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 TableNameADD ColumnName Properties
Here is an example:
ALTER TABLE StaffMembersADD 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 that allows empty 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 node. Under Table, drag Add Column and drop it in the query window. Delete the undesired sections of code and keep only the part that deals 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 Incrementproperty.
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 TableNameDROP COLUMN ColumnName
On the right side of the ALTER TABLE expression, type the name of the table. On the right side of the DROP COLUMN expression, enter the name of the undesired column. Here is an example:
ALTER TABLE StaffMembersDROP COLUMN CurrentResidence; GO
When this code is executed, the interpreter will look for a column named CurrentResidence in a table named StaffMembers of the 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 this, first display an empty query window and display the Templates Explorer. Expand the Table node. In the Table section, drag Drop Column and drop it in the query window. Delete the undesired sections of code and keep only the part that deals with adding a column. Here is 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, executesp_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.
|
Creating a User
|
Introduction |
Here is an example of creating a user:
CREATE USER [Raymond Kouma]FOR LOGIN rkouma;
GO
USE Exercise1;
GO
GRANT CREATE FUNCTION
TO rkouma;
GO
Databases Permissions: GRANT
| |
Introduction to Rights and Permissions |
Overview |
A permission is an action that a user is allowed to perform, or is prevented from performing, on a database or on one of its objects.
|
Granting a Permission |
In order to do something on the server or one of its objects, a user must be given the permission. This is also referred to as granting a permission. To grant permissions, the account you are using must have the ability to do so. This means that, before granting permissions, you must log in with an account that has its own right permissions. You can grant permissions visually or with code.
To visually grant one or more permissions on the server, in the Object Explorer, right-click the name of the server and click Properties. In the left frame of the Server Properties dialog box, click Permissions. In the Logins or Roles list, click the name of the user. In the bottom list, use the options in the Grant column:
The basic formula to programmatically grant one or more permissions is:
GRANT Permission TO Login
You start with the GRANT keyword followed by the name of the permission. After the permission, typeTO, followed by the login name you want to grant the permission to. Here is an example that gives operez to create a database on the server:
USE master;GO
GRANT CREATE ANY DATABASE
TO operez;
GO
If you want to grant more than one permission, separate their names with commas. Here is an example:
GRANT CREATE ANY DATABASE, SHUTDOWNTO operez;
GO
If you want to grant the same permission(s) to more than one account, list them, separated by commas. Here is an example:
GRANT CREATE ANY DATABASE, ALTER ANY LOGINTO pkatts, gdmonay;
GO
The DENY Permission
| |
Introduction |
A permission is an action that a user is allowed to perform, or is prevented from performing, on a database or on one of its objects.
|
Denying a Permission |
To visually deny one or more permissions, in the Object Explorer, right-click the name of the server and click Properties. In the left frame, click Permissions. In the Logins or Roles list, click the name of the user. Use the options in the Deny column.
The basic formula to programmatically deny one or more permissions is:
DENY Permission1,Permission2, Permission_nTO Login1, Login2, Login_n
Here is an example:
DENY CREATE ANY DATABASETO rkouma;
GO
Databases Permissions: REVOKE
| |
Introduction |
A permission is an action that a user is allowed to perform, or is prevented from performing, on a database or on one of its objects.
|
Revoking Permissions |
Revoking a permission consists of either denying a permission that was previously granted or granting a permission that was previously denied. To visually do this, open the Properties dialog box of the database (or the object) on which the permission was managed.
To programmatically revoke a permission, the formula to follow is:
REVOKE [ GRANT OPTION FOR ] <permission> [ ,...n ] { TO | FROM } <database_principal> [ ,...n ]
[ CASCADE ]
[ AS <database_principal> ]
<permission> ::= permission | ALL [ PRIVILEGES ]
<database_principal> ::= Database_user
| Database_role
| Application_role
| Database_user_mapped_to_Windows_User
| Database_user_mapped_to_Windows_Group
| Database_user_mapped_to_certificate
| Database_user_mapped_to_asymmetric_key
| Database_user_with_no_login
Start with the REVOKE keyword followed by the permission(s). This is followed by either TO orFROM and the login name of the account whose permission must be managed. Here is an example:
/*DENY CREATE ANY DATABASE
TO rkouma;
GO
*/
REVOKE CREATE ANY DATABASE
TO rkouma;
GO
Revoking a permission doesn't give that same permission. Imagine a user with a newly created account didn't have the permission to create new databases. If you deny that person the ability to create new databases, that denial becomes effective. If you revoke the permission, you are asking the server to restore the status of that person with regards to that particular right. That doesn't give that user the permission. The above code doesn't give the user the right to create new databases. If you want the user to have a right, you must explicitly grant the permission. Consider the following code:
REVOKE CREATE ANY DATABASETO rkouma;
GO
GRANT CREATE ANY DATABASE
TO rkouma;
GO
This restores the user's denial for creating new databases, then grants the permission to that user. This time, the user has the right to create new databases.
Databases Permissions: WITH GRANT
| |
Introduction to Rights and Permissions |
Overview |
A permission is an action that a user is allowed to perform, or is prevented from performing, on a database or on one of its objects.
|
Extending Permissions |
Besides granting or denying permissions to an account, you can give an account the ability to grant or deny permissions to other accounts. To do this visually, open the Database Properties for the database you want to work on. In the Users or Roles section, select the user. In the Persmissions, use the check boxes in the With Grant column.
The formula to programmatically give an account the ability to grant or deny permissions to other accounts is:
GRANT Permission1,Permission2, Permission_nTO Login1, Login2, Login_n
WITH GRANT OPTION
This follows the same formula as the GRANT right we saw earlier. You must just add the WITH GRANT OPTION expression.
A trigger is an action that is performed behind-the-scenes when an event occurs on a table or a view.
To better follow this lesson, you should use many user accounts as described in Lesson 1:
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
When a record has been removed from a table, you can apply a DML trigger in response. To make it possible, you can use the following formula:
CREATE TRIGGER TriggerNameON TableName AFTER/FOR DELETE AS TriggerCode
This time, the formula uses the DELETE operator as in AFTER DELETE or FOR DELETE. The other things follow the same description we saw for the INSERT operator.
When a DELETE trigger has acted on a table, the database engine creates a special temporary table named deleted. This table holds a copy of the records that were deleted. Eventually, if necessary, you can access this table to find out about those records.
GO
GO
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Schemas
| |
Introduction |
A schema is an object that contains other objects. Before using it, you must create it or you can use an existing schema. There are two types of schemas you can use, those built-in and those you create. When MicrosoftSQL Server is installed, it also creates a few schemas. One of the schemas is named sys. Another is called dbo.
|
The sys schema contains a list of some of the objects that exist in your database system. One of these objects is called databases (actually, it's a view). When you create a database, its name is entered in the databases list using the same name you gave it.
To access the schemas of a database, in the Object Explorer, expand the Databases node, expand the database that will hold or own the schema, and expand the Security node.
To visually create a schema, right-click Schemas and click New Schema...
This would open the Schema - New dialog box. In the Schema Name text box, enter a one-word name. Here is an example:
After providing a name, you can click OK.
The formula to programmatically create a schema is:
CREATE SCHEMA schema_name_clause [ <schema_element> [ ...n ] ]<schema_name_clause> ::=
{
schema_name
| AUTHORIZATION owner_name
| schema_name AUTHORIZATION owner_name
}
<schema_element> ::=
{
table_definition | view_definition | grant_statement |
revoke_statement | deny_statement
}
The most important part is:
CREATE SCHEMA schema_name_clause [ <schema_element> [ ...n ] ]
In this case, start with the CREATE SCHEMA expression and add a name to it. Here is an example:
1> CREATE SCHEMA PrivateListing;2> GO
1>
The other parts deal with issues we have not studied yet.
Accessing an Object From a Schema |
Inside of a schema, two objects cannot have the same name, but an object in one schema can have the same name as an object in another schema. Based on this, if you are accessing an object within its schema, you can simply use its name, since that name would be unique. On the other hand, because of the implied possibility of dealing with objects with similar names in your server, when accessing an object outside of its schema, you must qualify it. To do this, you would type the name of the schema that contains the object you want to use, followed by the period operator, followed by the name of the object you want to use. From our illustration, to access the Something1 object that belongs to Schema1, you would type:
Schema1.Something1
As mentioned already, when Microsoft SQL Server is installed, it creates a schema named dbo. This is probably the most common schema you will use. In fact, if you don't create a schema in a database, the dbo schema is the default and you can apply it to any object in your database.
To perform data entry on a table, you can click in a field and type the appropriate value.
To programmatically perform data entry, you use a Data Definition Language (DDL) command known as INSERT. The DDL command to perform data entry is INSERT combined withVALUES. The primary statement uses the following syntax:
INSERT TableName VALUES(Column1, Column2, Column_n);
An alternative is to add the INTO keyword after the INSERT keyword:
INSERT INTO TableName VALUES(Column1, Column2, Column_n)
The TableName factor must be a valid name of an existing table in the database you are using.
The VALUES keyword is followed by parentheses. In the parentheses, type the desired values:
| |||||||||||||||||||||||||
During data entry, users of your database will face fields that expect data. Sometimes, for one reason or another, data will not be available for a particular field. An example would be an MI (middle initial) field: some people have a middle initial, some others either don't have it or would not (or cannot) provide it. This aspect can occur for any field of your table. Therefore, you should think of a way to deal with it.
A field is referred to as null when no data entry has been made to it:
A field is referred to as null if there is no way of determining the value of its content (in reality, the computer, that is, the operating system, has its own internal mechanism of verifying the value of a field) or its value is simply unknown. As you can imagine, it is not a good idea to have a null field in your table. As a database developer, it is your responsibility to always know with certainty the value held by each field of your table.
A field is referred to as required if the user must provide a value for it before moving to another record. In other words, the field cannot be left empty during data entry.
To solve the problem of null and required fields, Microsoft SQL Server proposes one of two options: allow or not allow null values on a field. For a typical table, there are pieces of information that the user should make sure to enter; otherwise, the data entry would not be validated. To make sure the user always fills out a certain field before moving to the next field, that is, to require the value, if you are visually creating the table, clear the Allow Nulls check box for the field. On the other hand, if the value of a field is not particularly important, for example if you don't intend to involve that value in an algebraic operation, check its Allow Nulls check box.
If creating a table using SQL, to specify that it can allow null values, type NULL on the right side of the column. To specify that the values of the column are required, on the right side, typeNOT NULL. If you don't specify NULL or NOT NULL, the column will be created as NULL. Here are examples:
CREATE TABLE Persons( FirstName varchar(20) NULL, LastName varchar(20) NOT NULL, Gender smallint ); GO
If the table was already created and it holds some values already, you cannot set the Allow Nulls option on columns that don't have values.
After specify that a column would NOT allow NULL values, if the user tries creating a record but omits to create a value for the column, an error would display. Here is an example:
This error message box indicates that the user attempted to submit a null value for a column. To cancel the action, you can press Esc.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
* |
Records Operations: Updating a Record
|
Introduction |
Updating a record consists of changing or more of its values. To support this operation, the SQLprovides the UPDATE keyword you can use in the following formula:
UPDATE TableNameSET ColumnName = Expression |
Here is an example:
USE VideoCollection;GO UPDATE Videos SET Rating = 'R'; GO
Here is an example:
UPDATE TableNameSET ColumnName = Expression WHERE Condition(s)
Here is another example:
UPDATE VideosSET YearReleased = 1996 WHERE Director = 'Rob Reiner';
Here is another example:
UPDATE VideosSET YearReleased = 1996 WHERE VideoID = 5; GO
Here is an example:
UPDATE VideosSET Director = 'Jonathan Lynn' WHERE VideoTitle = 'The Distinguished Gentleman'; | ||||
SQL Operations: Deleting a Record
| ||||
Description |
To delete all records from a table, type DELETE followed by the name of the table, using this formula:
DELETE TableName;
Here is an example:
DELETE FROM Employees;
To delete a record, use this formula:
DELETE FROM TableNameWHERE Condition(s)
Here is an example:
DELETE FROM EmployeesWHERE EmployeeNumber = 24685; |
The Default Value of a Column
| |
Description |
A default value is one that a column would apply to its record if a value is not provided. You can assign a default value when creating a table in Design View or programmatically.
To visually specify the default value of a column, in the top section of the table in Design View, click the column. In the bottom section, click Default Value or Binding, type the desired value following the rules of the column's datatype.
|
To specify the default value in a SQL statement, when creating the column, before the semi-colon or the closing parenthesis of the last column, assign the desired value to the DEFAULT keyword. Here are examples:
CREATE TABLE Employees(
FullName NVARCHAR(50),
Address NVARCHAR(80),
City NVARCHAR(40),
State NVARCHAR(40) DEFAULT N'NSW',
PostalCode NVARCHAR(4) DEFAULT N'2000',
Country NVARCHAR(20) DEFAULT N'Australia'
);
GO
The default value can also come from a function. Here is an example:
CREATE TABLE Employees(
EmployeeName nvarchar(50),
DateHired date default GETDATE(),
Address nvarchar(50),
City nvarchar(40),
State nchar(2) DEFAULT 'VA',
PostalCode NVARCHAR(4),
Country NVARCHAR(20)
);
GO
If the table exists already and you want to add a column that has a default value, use the formula:
ALTER TABLE TableName ADD ColumnName Options
Here is an example:
USE Exercise1;GO
ALTER TABLE Employees
ADD HomePhone nvarchar(20) default N'(000) 000-0000';
GO
After creating the table, the user does not have to provide a value for a column that has a default. If the user does not provide the value, the default would be used when the record is saved.
A Column With Expression
| |
Description |
An expression used on a column is a combination of operators and operands used to produce the value of the column. The user will not enter a value for such a column.
To visually specify an expression for a column, display the table in Design View. In the top section, enter or select the column name. In the bottom section, expand the Computed Column Specification field and, in its (Formula) field, enter the desired expression. Here is an example:
|
To create an expression in SQL, in the placeholder of the column, enter the name of the column, followed by AS, and followed by the desired expression. Here is an example:
CREATE TABLE Circle(
CircleID int identity(1,1) NOT NULL,
Radius decimal(8, 3) NOT NULL,
Area AS Radius * Radius * PI()
);
GO
When performing data entry, you must not provide a value for a column that has an expression; the SQL interpreter would provide the value automatically. Here is an example of entering data for the above Circle table:
INSERT INTO Circle(Radius) VALUES(46.82);GO
INSERT INTO Circle(Radius) VALUES(8.15);
GO
INSERT INTO Circle(Radius) VALUES(122.57);
GO
Null Values on a Column
| |
Description |
A field is referred to as null if it has not received a value or its value is not clearly identified.
To visually create a null field, display the table in Design View. In the top section, click the column name. In its corresponding Allow Nulls section, check or clear the check box.
|
To specify the nullity of a column using SQL, on the right side of the column creation, type NULL. To specify that the values of the column are required, on the right side, type NOT NULL. If you don't specify NULL or NOT NULL, the column will be created as NULL. Here are examples:
CREATE TABLE Persons(
FirstName varchar(20) NULL,
LastName varchar(20) NOT NULL,
Gender smallint
);
GO
If the table was already created and it holds some values already, you cannot set the Allow Nulls option on columns that don't have values.
After specify that a column would NOT allow NULL values, if the user tries creating a record but omits to create a value for the column, an error would display. Here is an example:
This error message box indicates that the user attempted to submit a null value for a column. To cancel the action, you can press Esc.
Here is an example:
USE Exercise;GO CREATE TABLE Students ( StudentNumber int UNIQUE, FirstName nvarchar(50), LastName nvarchar(50) NOT NULL ); GO
When a column has been marked as unique, during data entry, the user must provide a unique value for each new record created. If an existing value is assigned to the column, this would produce an error:
USE Exercise;GO CREATE TABLE Students ( StudentNumber int UNIQUE, FirstName nvarchar(50), LastName nvarchar(50) NOT NULL ); GO INSERT INTO Students VALUES(24880, N'John', N'Scheels'), (92846, N'Rénée', N'Almonds'), (47196, N'Peter', N'Sansen'), (92846, N'Daly', N'Camara'), (36904, N'Peter', N'Sansen'); GO
By the time the fourth record is entered, since it uses a student number that exists already, the database engine would produce an error:
Msg 2627, Level 14, State 1, Line 2Violation of UNIQUE KEY constraint 'UQ__Students__DD81BF6C145C0A3F'. Cannot insert duplicate key in object 'dbo.Students'. The statement has been terminated. |
When performing data entry, in some columns, even after indicating the types of values you expect the user to provide for a certain column, you may want to restrict a range of values that are allowed. In the same way, you can create a rule that must be respected on a combination of columns before the record can be created. For example, you can ask the database engine to check that at least one of two columns received a value. For example, on a table that holds information about customers, you can ask the database engine to check that, for each record, either the phone number or the email address of the customer is entered.
The ability to verify that one or more rules are respected on a table is called a check constraint. A check constraint is a Boolean operation performed by the SQL interpreter. The interpreter examines a value that has just been provided for a column. If the value is appropriate:
If the value is not appropriate:
You create a check constraint at the time you are creating a table.
To create a check constraint, when creating a table, right-click anywhere in (even outside) the table and click Check Constraints...
This would open the Check Constraints dialog box. From that window, you can click Add. Because a constraint is an object, you must provide a name for it. The most important piece of information that a check constraint should hold is the mechanism it would use to check its values. This is provided as an expression. Therefore, to create a constraint, you can click Expression and click its ellipsis button. This would open the Check Constraint Expression dialog box.
To create the expression, first type the name of the column on which the constraint will apply, followed by parentheses. In the parentheses, use the arithmetic and/or SQL operators we studied already. Here is an example that will check that a new value specified for the Student Number is greater than 1000:
After creating the expression, you can click OK. If the expression is invalid, you would receive an error and given the opportunity to correct it.
You can create as many check constraints as you judge necessary for your table:
After creating the check constraints, you can click OK.
To create a check constraint in SQL, first create the column on which the constraint will apply. Before the closing parenthesis of the table definition, use the following formula:
CONSTRAINT name CHECK (expression)
The CONSTRAINT and the CHECK keywords are required. As an object, make sure you provide aname for it. Inside the parentheses that follow the CHECK operator, enter the expression that will be applied. Here is an example that will make sure that the hourly salary specified for an employee is greater than 12.50:
CREATE TABLE Employees( [Employee Number] nchar(7), [Full Name] varchar(80), [Hourly Salary] smallmoney, CONSTRAINT CK_HourlySalary CHECK ([Hourly Salary] > 12.50) );
It is important to understand that a check constraint it neither an expression nor a function. A check constraint contains an expression and may contain a function as part of its definition.
After creating the constraint(s) for a table, in the Object Explorer of Microsoft SQL Server Management Studio, inside the table's node, there is a node named Constraints and, if you expand it, you would see the name of the constraint.
With the constraint(s) in place, during data entry, if the user (or your code) provides an invalid value, an error would display. Here is an example:
Instead of an expression that uses only the regular operators, you can use a function to assist in the checking process. You can create and use your own function or you can use one of the built-in Transact-SQL functions.
| |||||||||||||||||||
Like a book, a table or a view can use the mechanism provided by an index. In a table or a view, an index is a column (or many columns) that can be used to locate records and take a specific action based on some rule reinforced on that (those) column(s).
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
We already know how to create a primary key on a table. Here is an example:
USE Exercise;GO CREATE TABLE Students ( StudentID int PRIMARY KEY, FirstName nvarchar(50) NOT NULL, LastName nvarchar(50)); GO
When you create a primary key, the database engine automatically creates an index on the table and chooses the primary key column as its key. You have the option of indicating the type of index you want created. To do this, on the right side of the name of the column, enter CLUSTERED orNONCLUSTERED. If you don't specify the type of index, the CLUSTERED option is applied.
GO
| ||||||||||||||||||||||||||||||||||||||||||
Comments
Post a Comment