Table Valued Functions in SQL Server – SQL Server Tutorial

Table Valued Functions in SQL Server  :-

  • These functions returns set of records  i:e table.
  • The return type of this functions must be “table”.
  • The return expression is  ”select statement”.

Syntax :-

               Create/alter function <name> (parameters)

                  Returns table

                   As

             Return(select statement).

Example  :-

           Create function getemp(@d  int)

           Returns table

                As

           Return(select * from emp where deptno=@d)

How to execute the function:

{The table valued functions are called in from clause of select statement}

Select * from dbo.getemp(10)

 

{i:e  it executes the all employees worked in 10th department}

Drop procedure in SQL Server  :-

      Drop procedure <name>

Drop function in SQL Server :-

           Drop function<name>

Function Types in SQL Server – SQL Server Tutorial

Function Types in SQL Server   :-

It can be divided into two types

  1. Scalar valued
  2. Table valued

Scalar Valued function in SQL Server:-

These functions returns only one value of type int,varchar date time etc.

Syntax  :–

                 Create/alter function <name>(parameters)

                     Returns <type>

                          As

                       Begin

                       Statements

                    Return<exper>

                         End.

Example  :-

            Create function addnum(@x int,@y int)

                  Returns  int

                      As

                    Begin

                   Declare @z int

                Set @z=@x+@y

                   Return @ z.

                  End.

Executing the function using select statement  :

Select dbo.addnum(10,20)

 Executing the function from another tsql block :

               Declare @ a  int,@b int,@c int

                    Set @a=30

                     Set @b=50

                       Set @c=dbo.addnum(@a,@b)

                   Print @c

Program  :

Create a function to calculate employee experience?

                    Create function expr( @e int)

                       Returns int

                            As

                         Begin

                       Declare  @doj datetime,@x int

                  Select      @doj=hiredate  from    emp

                                             Where empno=@e

                        Set @x =abs(datediff(yy,getdate(),@doj))

                        Return @x

                           End

                                  ↓

                           Select dbo.expr(7566)

                                   ↓

Write a program to print all employee names and their experience?

                                  ↓

Select ename,dbo.expr (empno) from exp.

Write a program to calculate the employee experience,if experience≤30 then increment the emp salary by 10% otherwise delete the record from table :-

                   Declare c1 cursor for

                        Select empno from emp                           →hiredate

                 Declare @eno int,@x int                                →@doj date time

                     Open c1

                Fetch next from c1 into @eno                                  →@doj

                While(@@fetch_status=0)

                     Begin

                      Set @x=dbo.expr(@eno)

                        If @x<=30

                    Update emp set sal=sal*1.1

                             Where emp no=@eno

                              Else

                          Delete from emp where empno=@eno

                       Fetch next from  c1 into @eno

                               End

                         Close c1.

Example  :-

                    Create function expr(@doj datetime)

                    Returns int

                     As

                    Begin

                     Declare @x int

               Set @x=abs[datediff(yy,getdate(),@doj))

                  Return @x

                   End

Acct_mast:

          Accno    accname     bal

Acc_trans:-

Trid       ttype tdate         tamt         accno.

procedure for new account  :-

Create  procedure    new_acct(@ a   int,@n  varchar(20),@b  money)

                        As

                       Begin

              Insert into acct_mast values(@a,@n,@b)

                 End.

                    ↓

Exec   new_acct 1,’A’,5000.

Procedure for {closing} close_acct :-

              Create procedure close_acct(@a int)

                    As

                   Begin

                Delete from   acct_mast where accno=@a

                   End.

Procedure for credit  :-

            Create procedure credit(@a int,@amt money)

               As

              Begin

             Update acct_mast set bal=bal+@amt

                             Where accno=@a.

              Insert into acct_trans(ttype,tdate,tamt,acno)

                                      Values (‘D’ ,getdate(),@amt,@a)

                       End.

Procedure for Debit  :-

  Create procedure debit(@a  int,@amt money)

   As

  Begin

Update acct_mast set bal=bal-@amt

                    Where accno=@a

  Insert into acct_trans(ttype,tdate,tamt,accno)

           Values(‘w’,getdate ( ),@amt,@a)

  End.

Procedure for money transfer :-

          Create  procedure transfer(@s  int,@t int,@amt money)

            As

     Begin

     Update acct-mast set bal=bal-@amt  where accno=@s

      Update acct-mast  set bal =bal+@amt  where accno=@t.

      Insert into acct_trans(ttype,tdate,tamt,accno)values 

                                      (‘w’,getdate ( ),@amt,@s).

         Insert into acct-trans(ttype,tdate,tamt,accno)

                   Values(‘D’,getdate ( ),@amt,@t).

                End.

@@Rowcount  :-

It returns no. of records effected by the sql statement.

         →update

                @c1=@@rowcount

                  Update

                @c2=@@rowcount

                    Insert

                    Insert

                If @c1=@c2

               Commit

                 Else

                  Rollback.

Procedure for balance  :

          Create function balance(@a  int)

              Returns money

            As

         Begin

      Declare @bal money

    Select  @bal =bal from acct-mast

                      Where accno=@a

         Return @bal

          End.

Difference between Procedures and Functions in SQL Server Tutorial

Functions in SQL Server :-

  • A function is also a named tsql block takes some input performs a task and must returns a value.

Difference between Procedures and Functions in SQL Server:

Procedures :

  • A procedure need not return a value.
  • Returns values using out parameters.
  • procedure can return more than one value
  • procedure can’t be called in select statement.                                                                                   

 Functions :

  • Function must return a value.
  • Function returns  value using return expression.
  • Function can return only one value.
  • But function can be called in select Statement.

User Defined Errors SQL Server – SQL Server Tutorial

User Defined Errors SQL Server :-

  • These errors are defined by user.
  • These errors are raised by using the following statement

                     Raiserror (error number/error message, error level, error state).

Example  :-  Of user defined error : Create procedure div(@x  int,@y int)

                               As

                            Begin

                           Begin try

                          Declare   @z int

                      If @y=1

              Raiserror(‘divide by one error’,15,1)

                  Set @z=@x/@y

                   Print @z

                    End try

                   Begin catch

             Print error_message ( )

                   End catch

                     End

                        ↓

                     Exec  div  10,1

                          ↓

Output → divide by one error.

Create table emp_temp :-

            (eno int,ename varchar(20),sal smallmoney)

To create a procedure to insert the record into emp_temp.

Create procedure

                Insert  _rec(@e int,@n varchar(20),@s smallmoney)

                As

               Begin

              Begin try

          If exists (select * from emp_temp where eno=@e)

              Raiserror(‘employee already exists’,15,1)

               If @s<3000

             Raiserror(‘sal>3000’,15,1)

   Insert into emp_temp values (@c,@n,@s)

         End try

     Begin catch

   Print error_message()

End catch

End

   ↓

Exec  insert

Sp_addmessage  :-

Built-in procedure used to add our errors to sys.message table.

Example  :- sp_addmessage 50005,15,’employee already exists’

                                       ↓

            Select * from sys.messages.

Program :- Create procedure

                 Insert _rec(@e int,@n varchar(20) ,@s  smallmoney)

                     As

                Begin

               Begin try

If exists (select * from emp_temp

                               Where eno=@e)

  Raiserror(50005,15,1)

 If @s<3000

   Raiserror(‘sal>3000’,15,1)

Insert into emp_temp values (@e,@m,@s)

     End try

    Begin catch

    Print error_messge ( )

       End catch

    End.

Functions in Exceptions Handling – SQL Server Tutorial

Functions in exceptions handling :

  • Error_number:- This function returns error number.
  • Error_message:- It returns the error message.
  • Error_line:- It returns  the line number.
  • Error_severity:- It returns error severity level.
  • Error_state:- It returns error state level.

Every error has got mainly 4 parts :-

  1. error_number
  2. error_message
  3. error_level
  4. error_state

select * from sys.messages

This table maintains the list of errors.

System defined error is up to 50,000 errors and above 50,000 is user defined errors.

Security level :-

 

  • The severity level between  1 to 25
  • If severity  level is between 20 to 25 those errors are called ”fatal error”, if this fatal error occurs then client connection will be terminated.

State level  :-

  • It is used in user defined errors.

Example :-

Create procedure div(@x int,@y int)

As

Begin

Begin try

Declare @z  int

Set    @z  =1

Set @z=@x/@y

Print @z

End try

Begin catch

Print error_message()

End catch

End.

Example :- create procedure insert_rec (@e int,@n varchar, @s  int)

As

Begin

Begin try

Insert into emp_temp values(@e,@n,@s)

End try

Begin catch

If error_number()=547

Print ‘check constraint vioated’

Else if error_number ()=2627

Print ‘primery key violated’

End catch

End

Exec   insert_rec 1,’a’,1000

Error Handling and Exception Handling in SQL Server – SQL Server Tutorial

Error Handling and Exception handling in SQL Server:-

  • An exception means “ Run time error”
  • In SQL server if any statement causes run time error then SQL Server returns “error msg” and program execution is continued.
  • When any error occurs to display user friendly message and to execute error processing statements and the error must be handled.
  • To handle errors we need to provide a block called “try-catch block”.

Syntax :

Create procedure <name> (parameter)

As

Begin

Begin try

Statements → it is causes error

End try

Begin catch

Statements → it is handle error

End catch

End.

if any statement in try block causes exception then control is transfer to catch block and statements in the catch block are executed.

 Example  :-

Create procedure div (@x int ,@y int)

As

Begin

Begin try

Declare @z int

Set @z=@x/@y

Print @ z

End try

Begin catch

Print   ‘ divide by zero error’

End catch

End

↓                                             ↓

Exec div 10,5                  Exec div 10,0

↓                                             ↓

Output → 2                    Output → divide by zero error.

Declaring Parameters with Default Values – SQL Server Tutorial

Declaring parameters with default values :-

If  parameters are declared with default value at the time of calling procedure if the value is not passed to the parameter then default value assigned to that parameter.

Example  :-@x int =10

Example :-  

alter procedure

Addnum (@x  int,@y  int=20,@z int output)

As

 Begin

Set @z=@x+@y

End.

 Declare   @ k int

 Excute addnum 10,default,@k output

Print   @k

Note :-  In procedures we have 10 default values,int that case we go for named position and execute as follows:-

           Declare  @a int, @b int, @k int

                   Set @a=10

           Execute addnum  @x=@a,@z=@k output

                    Print @ k.

Create a procedure to increment particular employee salary by particular percentage :-

                Create procedure

              Updsal(@e int,@p int,@s smallmoney output)

                  As

                 Begin

                    Update emp set sal=sal+(sal*@p/100)

                                  Where empno=@e

                      Select @s=sal from emp where empno=@e

                        And.

  • Write a program to I/P employee number and percentage and increment the salary by that %
  • After increment if salary exceeds 5000 then cancel that update.

                         Set implicit_transaction on

                        Declare @eno int  @pen  int,   @sal smallmoney

                       Set @eno=7566

                       Set @pen=70

              Execute updsal @eno,@pen,@sal output.

                If @sal>5000

                       Rollback

                    Else

                 Commit.

Procedures in SQL Server – SQL Server Tutorial

Procedures in SQL Server :-

  • A procedure is a pre-compiled named block stored in database that performs a task & may (or) mayn’t return a value.
  • Procedures are stored in database, so it is called “stored procedures”
  • Procedures are created to perform DML operations over database [transactions].

Syntax for creating procedure :

Create/alter procedures <name> → procedure declaration

(Parameters)

As

Begin

            Statements → procedure body

End.

Parameters are two types :–

  • Formal
  • Actual

Example :- 

                k= add(a,b)

                Int add(int x,int y)

                 {

                    Return x+y;

                   }

parameters which are declared in procedures declaration that called “formal parameter”

Parameters  which are passed at the time of calling procedure are called “actual parameter”.

Formal & actual parameters are two types  :-

  1. Input
  2. Output

Input  :-

  • Input parameters are always receive value in a program and it is a default and it is read only.

Output :-

  • output parameters are always sends value to  main program.
  • And it is write only

Example for input Parameter :-

Create a procedure to add two numbers  :-

      Create procedures addnum(@x int,@y int)

                   As

                  Begin

                  Declare    @z  int

                  Set @ z=@x+@y

                    Print  @z

      End

  • Once procedure is created the procedures can be executed from [SSMS] SQL Server management studio (or) .net application (or) java application etc.
  • In SSMS, procedures can be executed in two ways:

               (I) Positional notation

               (II) Named notation

(I) Positional notation in SQL  :-

  • In positional rotation parameters are mapped through their position.

Example:  (how to execute the above procedure) in positional notation.              

Execute addnum  50,30

(II) Named notation in SQL  :-

  • In named notation the parameter are mapped through their names.

Example  :-   {how to execute the above procedure in named notation}

                   Declare @a int,@b int

                  Set   @ a=40

                   Set @ b=60

          Execute addnum   @y=@b,@x=a(or)

                                         @x=@a,@y=@b

Output parameter example  :-

   Alter procedure

  Addnum(@x int,@y int,@z  int output)

     As

    Begin

  Set @z=@x+@y

     End

How to execute  :-

               Declare @a int,@b int,@c int

                 Set @a=30

                 Set @b=40

          Execute addnum @a,@b,@c output

              Print @c.

Sub-Programs in SQL Server – SQL Server Tutorial

Sub-Programs in SQL Server  :- 

Named blocks:

  1. Procedures
  2. Functions
  3. Db triggers

procedures & functions are also called “sub-programs”

subprograms means called in main program.

Difference between Anonymous and named:

Anonymous named
  • Block without name
  • anononymous blocks are saved in “operating system file”
  • These blocks are not secured. 
  • These blocks can’t be re-used. 
  • Every time compile & executed.  
  • blocks with name.
  • but the named blocks are saved in “database”
  • but named blocks are secured.
  • but named blocks can be re-used.
  • Named blocks are one time compilation And every time execution

Main advantages of creating procedures and functions :-

(I) Reusability

(II) Pre-compiling

Local and Global Cursors – SQL Server Tutorial

Local and Global Cursors  :-

  • If cursor is local then the cursor can access with in the program only.
  • If cursor is global then the cursor can be declared in one progress can be used in another program.

Global is default

Program (I) :-

             Declare c1 cursor global

                      For select ename,sal,comm from emp.

               Declare  @ename varchar(20)

                Declare @sal smallmoney  @comm smallmoney.

                Declare @totsal smallmoney.

                            Open c1

                           Fetch next from c1 into @ename,@sal,@comm

                            While (@@fetch_status=0)

                                 Begin

                              Set @totsal=@sal+isnull(@comm,0)

                              Print  @ename+’earns’+cast(@total as varchar)

                         Fetch next from c1 into @ename,@sal,@comm

                          End.

                             Close c1.

Note  :-

Program(II)  :-  Calculating   annual salary using cursor c1:

                                        Declare  @ename varchar(20)

                                         Declare   @sal smallmoney,@comm smallmoney

                                         Declare @totsal smallmoney

                                              Opn c1

                                      Fetch next from c1 into @ename,@sal,@comm

                                       While (@@fetch_status=0)

                                         Begin

                                          Set @totsal=(@sal+isnull(@comm,0))*12

                                          Print  @ename+’earns’+cast(@totsal as varchar)

                                        Fetch next from c1 into @ename,@sal,@comm

                                           End

                                         Deallocate c1.

                            Order_details                                     items

      Ordno         icode             qty                     icode         descrpt        price

          1000           1                   10                        1                                  100

         1000            2                   30                         2                                  150

          1000           3                   15                         3                                  50

          1001           1                 20

To display like :-   

              Item code             dept                 rate            qty             value

                   1                         —                   100            10               1000

                   2                         —                    150            20              3000

                   3                         —                    50              15               750

Total bill=4750

Program :-

                        Declare   c1   cursor

                            For select    icode,descno,rate,qty

                               From   order-details,items

                      Where   order_details icode=items.icode

                                     And      andno=1000.

                      Declare @icode int,@descrip varchar(20)

                      Declare   @rate   int,@qty int

                         Declare @value int

                        Declare   @tbil int.

                       Set @tbil=0

                    Open c1

    Fetch  next from c1 into @icode,@descrip,@rate,@qty

                    While (@@fetch_status=0)

                   Begin

                   Set @value=@qty*@rate

       Set   @tbill=@tbill+@value

          Print  cast (@icode as varchar)+’ ’+@descrip+

                 ‘ ‘+cast(@rate as varchar) +’ ‘+cast+@qty

                          As varchar)+cast(@value as varchar)

                   Fetch next from c1 into @icode,@descrip @rate@qty.

                    End

                       Print ‘total bill :-‘+cast(@tbill as varchar)

                        Close c1

                     Deallocate c1.