Anda di halaman 1dari 14

MS SQL Server - Transact-SQL Topics

IF a Condition is True
To find out whether a condition is true, you use the IF operator of Transact-SQL
. Its basic formula is:
IF Condition
Statement
When creating an IF statement, first make sure you provide a Condition expression that can
be evaluated to produce true or false. To create this Condition, you can use variables and the
logical comparison operator reviewed above.

When the interpreter executes this statement, it first examines the Condition to evaluate it to a tru
Condition produces true, then the interpreter executes the Statement. Here is an example:
DECLARE @DateHired As datetime2,
@CurrentDate As datetime2
SET @DateHired = N'1996/10/04'
SET @CurrentDate = N'2007/04/11'
IF @DateHired < @CurrentDate
PRINT N'You have the experience required for a new promotion in this job'
GO
This would produce:

IF...ELSE

The IF condition we used above is appropriate when you only need to know if an expression is true. Th
do in other alternatives. Consider the following code:
DECLARE @DateHired As datetime2,
@CurrentDate As datetime2
SET @DateHired = N'1996/10/04'
SET @CurrentDate = N'2007/04/16'
IF @DateHired > @CurrentDate
PRINT
N'You have the experience required for a new promotion'
GO
This would produce:

Notice that, in case the expression to examine produces a false result, there is nothing to do. Som
happen.

INDEX
An index is a technique of setting a rule that must be respected with regards to records,
especially during data entry. Here is an example:
-- =============================================
-- Create index basic template
-- =============================================
USE Exercise1;
GO
CREATE TABLE dbo.Employees
(
EmployeeNumber integer NOT NULL,
FirstName varchar(50) NULL,
LastName varchar(50) NOT NULL,
HourlySalary decimal(6, 2)
)
GO
CREATE INDEX IDX_EmployeeNumber
ON dbo.Employees(EmployeeNumber);
GO

Microsoft SQL Server Operators:


CASE...WHEN...THEN
Introduction
The CASE keyword
is used as a conditional operator that considers a value, examines it, and acts on an option depending
on the value. The formula of the CASE statement is:

CASE Expression
WHEN Value1 THEN Result
WHEN Value2 THEN Result
WHEN Value_n THEN Result
END
In the following example, a letter that represents a student is provided. If the letter is m
or M, a string is created as Male. If the value is provided as f or F, a string is created as
Female:
DECLARE @CharGender Char(1),
@Gender Varchar(20);
SET @CharGender = 'F';
SET @Gender =
CASE @CharGender
WHEN N'm' THEN
WHEN N'M' THEN
WHEN N'f' THEN
WHEN N'F' THEN
END;

N'Male'
N'Male'
N'Female'
N'Female'

SELECT N'Student Gender: ' + @Gender;


GO
Here is the result of executing it:

CASE...WHEN...THEN...ELSE
In most cases, you may know the only types of value that would be submitted to a CASE
statement. In some other cases, an unpredictable value may be submitted. If you
anticipate a value other than those you are aware of, the CASE statement provides a "fitall' alternative by using the last statement as ELSE. In this case, the formula of the CASE
statement would be:
CASE Expression
WHEN Value1 THEN Result
WHEN Value2 THEN Result
WHEN Value_n THEN Result
ELSE Alternative
END
The ELSE statement, as the last, is used when none of the values of the WHEN statements
fits. Here is an example:
DECLARE @CharGender Char(1),
@Gender Varchar(20);
SET @CharGender = 'g';
SET @Gender =
CASE @CharGender
WHEN N'm' THEN
WHEN N'M' THEN
WHEN N'f' THEN
WHEN N'F' THEN
ELSE 'Unknown'
END;

N'Male'
N'Male'
N'Female'
N'Female'

SELECT N'Student Gender: ' + @Gender;


GO
This would produce:

If you don't produce an ELSE statement but a value not addressed by any of the WHEN
statements is produced, the result would be NULL. Here is an example:

WHILE
Introduction
To examine a condition and evaluate it before taking action, you can use the WHILE
operator. The basic formula of this statement is:
WHILE Expression
Statement
When implementing this statement, first provide an Expression after the WHILE
keyword. The Expression must produce a true or a false result. If the Expression is
true, then the interpreter executes the Statement. After executing the Statement, the
Expression is checked again. AS LONG AS the Expression is true, it will keep executing
the Statement. When or once the Expression becomes false, it stops executing the
Statement.
This scenario can be illustrated as follows:

Here is an example:
DECLARE @Number As int
WHILE @Number < 5
SELECT @Number AS Number
GO
To effectively execute a while condition, you should make sure you provide a mechanism for the interpreter
to get a referenced value for the condition, variable, or expression being checked. This is sometimes in the
form of a variable being initialized although it could be some other expression. Such a while condition could be
illustrated as follows:

This time, the statement would be implemented as follows:


DECLARE @Number As int
SET @Number = 1
WHILE @Number < 5
BEGIN
SELECT @Number AS Number
SET @Number = @Number + 1
END
GO
This would produce:

This means that it is a valuable safeguard to always include an ELSE sub-statement in a


CASE statement.

SQL Built-In Stored Procedures


Renaming an Object
To rename an object that was created in the current database, you can call the sp_rename stored
procedure. Its syntax is:
sp_rename [ @objname = ] 'object_name' , [ @newname = ] 'new_name'
[ , [ @objtype = ] 'object_type' ]
The object_name is the name of the object you want to delete.
The new_name is the new name the object will have.
The object_type is option. It allows you to specify the type of object you are trying to rename.
The sp_rename stored procedure can be used to rename a table. Here is an example:
USE Exercise;

GO
EXEC sp_rename N'Contractors', N'Employees';
GO
When this code runs, a table named Contractors will have its name changed to Employees.
The sp_rename stored procedure can also be used to rename a column or an index. In this case, the
name of the object must be qualified.

Sending Email
To give you the ability to send an email from a database, Transact-SQL provides the sp_send_dbmail
stored procedure. This store procedure is created in the msdb database. This means that you must
reference it when executing this procedure. It's syntax is:
sp_send_dbmail [ [ @profile_name = ] 'profile_name' ]
[ , [ @recipients = ] 'recipients [ ; ...n ]' ]
[ , [ @copy_recipients = ] 'copy_recipient [ ; ...n ]' ]
[ , [ @blind_copy_recipients = ] 'blind_copy_recipient [ ; ...n ]' ]
[ , [ @subject = ] 'subject' ]
[ , [ @body = ] 'body' ]
[ , [ @body_format = ] 'body_format' ]
[ , [ @importance = ] 'importance' ]
[ , [ @sensitivity = ] 'sensitivity' ]
[ , [ @file_attachments = ] 'attachment [ ; ...n ]' ]
[ , [ @query = ] 'query' ]
[ , [ @execute_query_database = ] 'execute_query_database' ]
[ , [ @attach_query_result_as_file = ] attach_query_result_as_file ]
[ , [ @query_attachment_filename = ] query_attachment_filename ]
[ , [ @query_result_header = ] query_result_header ]
[ , [ @query_result_width = ] query_result_width ]
[ , [ @query_result_separator = ] 'query_result_separator' ]
[ , [ @exclude_query_output = ] exclude_query_output ]
[ , [ @append_query_error = ] append_query_error ]
[ , [ @query_no_truncate = ] query_no_truncate ]
[ , [ @mailitem_id = ] mailitem_id ] [ OUTPUT ]
As you may guess, most of the arguments are optional. Otherwise:
The profile_name value must hold a valid for an existing profile. If you omit this argument, the
database engine uses the current user or a default profile created in the msdb database. If there is
no default profile, you must create one. To do this, in the Object Explorer, expand the Management
node and double-click Database Mail. A wizard would start:

Click Next. If you are trying a new profile, click the first radio button:

Click Next. This would bring the third page of the wizard:

In the Profile Name text box, enter the desired name. If you want, type some explanation in the Description
text box. To specify an account that can send emails, click Add and fill out the form. Once you are ready,
click OK. If you want to add another profile, click Add again, fill out the form, and click OK. On the third page
of the wizard, click Next twice. When the wizard has finished, click Close.

The recipients value represents one or more email addresses that will receive the message. If you want
to send the message to only one recipient, provide the address. To get the message to more than one
recipient, separate their email addresses with commas
The copy_recipient value represents one or more email addresses that will receive a copy of the
message. This is equivalent to cc. To send the message to one recipient, provide the address. To send
the message to many recipients, provide the necessary email addresses separated by commas
The blind_copy_recipient value follows the same rules as the copy_recipient argument except that the
recipients will not see each other's email address. This is equivalent to bcc
The subject value is the subject of the message

The body value is the actual message to send


The body_format value specifies the format to use
The importance value specifies the level of importance of the message
The sensitivity value specifies the type of sensitivity of the message
Here is an example of executing this stored procedure:
USE Exercise;
GO
EXEC msdb.dbo.sp_send_dbmail
@profile_name = N'Central Administrator',
@recipients = N'jaywiler@hothothot.net',
@body = N'The Persons table has received a new record.',
@subject = N'New Record';
GO
Before executing this procedure, you should check the security settings on your server. Otherwise you may
receive an error. Here is an example:
Msg 15281, Level 16, State 1, Procedure sp_send_dbmail, Line 0
SQL Server blocked access to procedure 'dbo.sp_send_dbmail' of component 'Database
Mail XPs' because this component is turned off as part of the security configuration
for this server. A system administrator can enable the use of 'Database Mail XPs'
by using sp_configure. For more information about enabling 'Database Mail XPs',
see "Surface Area Configuration" in SQL Server Books Online.
To solve this problem, open a Query window and type the following:
sp_configure N'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure N'Database Mail XPs', 1;
GO
RECONFIGURE;
GO

Anda mungkin juga menyukai