Advertisement

Latest Post

Saturday, 24 September 2016

BEGIN and END keyword in Sql server

Hello guys , I am sharing BEGIN and  END keyword with you.


BEGIN and END keyword

The BEGIN and END statements are used to group queries into a  block or we can say it defined the start and end of the block.

Syntax:

BEGIN
/// Write here sql statement

END

Example:

BEGIN
      DECLARE @result VARCHAR(255)
      SET @result = (SELECT RegionName FROM Regions WHERE RegionId=@RegionId)
      RETURN ISNULL(@result,'')

END

The BEGIN and END are used on following conditions with example:

1:-With WHILE loop  block of queries.

WHILE condition
BEGIN
   {...statements...}
END;

2:-With CASE block of statements

BEGIN
      -- Declare the return variable here
      DECLARE @result VARCHAR(100)

      SET @result = (SELECT
      CASE WHEN @EnumId = 1 THEN 'Active'
             WHEN @EnumId = 2 THEN 'Deceased'
             WHEN @EnumId = 3 THEN 'Inactive'
             WHEN @EnumId = 4 THEN 'Discharged'
             ELSE
             ''
      END)
           
      RETURN @result
END

3:-With IF or ELSE  block of statements

BEGIN
      -- Declare the return variable here
      DECLARE @result VARCHAR(50)

      IF @CodeId IS NULL
      BEGIN
            SET @result=''
      END
      ELSE
      BEGIN
            SET @result = (SELECT BillCode FROM tblCodes WHERE   CodeId=@CodeId)
      END  
      RETURN ISNULL(@result,'')
END 

Government Jobs