Search This Blog

Thursday 5 February 2015

User Defined Function in SQL Server?

Step 1 :-

1. Scalar User Defined functions

Create function Calculate(@AA int,@BB int)

returns int

as

begin

       declare @A int

       declare @B int

       declare @C int

       set @A=@AA

       set @B=@BB

       set @C=@A+@B

return @C


end


select dbo.Calculate(2,2)



2. Inline Table Valued function


Create Function InlineTableValuedEX()

Returns Table

as

Return

(

       Select * from 'Your Table Name'

)


select * from dbo.InlineTableValuedEX()



3. Multi-statement Table Valued function


Create function TableValuedEX(@AA int,@BB int)

returns @temptable TABLE (items varchar(8000))

as

begin

       declare @A int

       declare @B int

       declare @C int


       set @A=@AA

       set @B=@BB

       set @C=@A+@B


       insert into @temptable(items) values(@C)

return

end


select items from dbo.TableValuedEX(2,2)



Note : 


1.Scalar functions may or may not have parameters, but always return a single (scalar) value. 



1. In an Inline Table Valued function, the RETURNS clause cannot contain the structure of  the table, 
    the function returns.
2. Inline Table Valued function cannot have BEGIN and END block



     1.  In an multi-statement Table Valued function, the RETURNS clause contain the structure of the table, the function returns.
     2.  multi-statement Table Valued function have BEGIN and END block


No comments:

Post a Comment