Encloses a series of Transact-SQL statements that will execute as a group. BEGIN...END blocks can be nested.
BEGIN
{sql_statement | statement_block}
END
Boolean
This example produces a list of business books that are priced less than $20 when one or more books meet these conditions. Otherwise, SQL Server prints a message that no books meet the conditions and a list of all books that cost less than $20 is produced.
SET NOCOUNT OFF
GO
USE pubs
GO
SET NOCOUNT ON
GO
DECLARE @msg varchar(255)
IF (SELECT COUNT(price)
FROM titles
WHERE title_id LIKE 'BU%' AND price < 20) > 0
BEGIN
SET @msg = 'There are several books that are a good value at under $20. These books are: '
PRINT @msg
SET NOCOUNT OFF
SELECT title
FROM titles
WHERE price < 20
END
ELSE
BEGIN
SET @msg = 'There are no books under $20. '
PRINT @msg
SELECT title
FROM titles
WHERE title_id
LIKE 'BU%'
AND
PRICE <10
END
Here is the result set:
There are several books that are a good value at under $20. These books are:
title
------------------------------------------------------------------------
The Busy Executive's Database Guide
Cooking with Computers: Surreptitious Balance Sheets
You Can Combat Computer Stress!
Straight Talk About Computers
Silicon Valley Gastronomic Treats
The Gourmet Microwave
Is Anger the Enemy?
Life Without Fear
Prolonged Data Deprivation: Four Case Studies
Emotional Security: A New Algorithm
Fifty Years in Buckingham Palace Kitchens
Sushi, Anyone?
(12 row(s) affected)
ALTER TRIGGER | Control-of-Flow Language |
Batches | ELSE (IF...ELSE) |
BEGIN...END | IF...ELSE |
CREATE TRIGGER | WHILE |