Sunday, February 28, 2016

User Defined Function (UDF) In SQL SERVER

Content
  1. Introduction
  2. Scalar functions
  3. Inline table valued function
  4. Multi-statement table valued functions
Introduction
  • SQL server provides list of many predefined functions that are built in to the T-SQL language
  • The main benefit of UDF is that we are not just limited to SQL provided functions.
  • We can write our own functions to meet our specific needs or to simplify complex SQL codes.
Types of User Defined Functions

  • SQL Server supports two types of User Defined Functions
    • Scalar Functions – The function which returns a Scalar/Single value
    • Table Valued Functions – The function which returns a row set of SQL server Table datatype. Table Valued Functions can be written as 
      • Inline Table
      • Multi-statement Table


1. Scalar Function
  • They are like standard built in functions provided with SQL Server.
  • They return scalar values that can be used anywhere a constant expression can be used.
  • They typically take one or more arguments and returns a value of a specified data types.
  • Every T-SQL function must return a result using the RETURN statement.
Syntax

CREATE FUNCTION fnName ([param,..])
RETURNS DataType AS
BEGIN
Statement RETURN DataType
END

Example

CREATE FUNCTION [dbo].[fnResult](@score int)
RETURNS VARCHAR(1) 
BEGIN 
DECLARE @s VARCHAR(1)
IF @score <50
SET @s='F'
ELSE IF @score <60
SET @s= 'E'
ELSE
SET @s= 'A'
RETURN @s
END

Call Function 
DECLARE @result CHAR(1)
SET @result=dbo.fnResult(50)
SELECT @result

2. Table Value Function


  • A table-valued user-defined function returns a rowset instead of a single scalar value.
  • Can be invoked in the FROM clause of a SELECT statement, just as we would a table or view.
  • A table-valued function can almost be thought of as a view that accepts parameters, so the result set is determined dynamically.
  • A table valued function specifies the keyword TABLE in its RETURNS clause.
a) Inline table valued function

  • An inline table-valued function specifies only the TABLE keyword in the RETURNS clause, Without table definition information.
  • The code inside the function is a single RETURN statement that invokes a SELECT statement.
Syntax

CREATE FUNCTION fName([param],..)
RETURNS TABLE
AS
RETURN (SELECT Statement)

Example

CREATE FUNCTION fnResultList ()
RETURNS TABLE
AS
RETURN (SELECT score.id,student.Studentname,[subject].[name] as Subjects,score,
[dbo].[fnResult](score) as result 
FROM SCORE inner join Student on score.studentid=student.StudentId 
inner join [Subject] on score.subjectid=[subject].id)



b) Multi statement table valued function

  • Multi-statement table-valued functions differ from inline functions in two major ways
    • The RETURNS clause specifies a table variable and its definition.
      • The body of the function contains multiple statements, at least one of which populates the table variable with data values.

  • The scope of the table variable is limited to the function in which it is defined.
  • Within the function in which a table variable is defined, that table variable can be treated like a regular table. You can perform any SELECT, INSERT, UPDATE, or DELETE statement on the rows in a table variable, except for SELECT INTO.



Syntax

CREATE FUNCTION fName([param]..)
RETURNS @tableName TABLE (field DataType,…)
AS
BEGIN
INSERT INTO @tableName
SELECT field,..
FROM tableName
RETURN

END

Example

CREATE FUNCTION fnResultListWithCondition(@status CHAR(10))
RETURNS @table TABLE (id INT,studentname VARCHAR(50),[subject] VARCHAR(50),
score INT,Result CHAR(1))
AS

BEGIN
IF @status='pass'
BEGIN
INSERT INTO @table
SELECT score.id,student.Studentname,[subject].[name] as Subjects,score,
[dbo].[fnResult](score) as result
FROM SCORE inner join Student on score.studentid=student.StudentId
inner join [Subject] on score.subjectid=[subject].id
WHERE score.score>=50
END

ELSE IF @status='fail'
BEGIN
INSERT INTO @table
SELECT score.id,student.Studentname,[subject].[name] as Subjects,score,
[dbo].[fnResult](score) as result
FROM SCORE inner join Student on score.studentid=student.StudentId
inner join [Subject] on score.subjectid=[subject].id
WHERE score.score<50
END
ELSE
BEGIN
INSERT INTO @table
SELECT score.id,student.Studentname,[subject].[name] as Subjects,score,
[dbo].[fnResult](score) as result
FROM SCORE inner join Student on score.studentid=student.StudentId
inner join [Subject] on score.subjectid=[subject].id
END
RETURN
END

Call Function

SELECT * FROM [dbo].[fnResultListWithCondition] ('fail')
SELECT * FROM [dbo].[fnResultListWithCondition] (‘pass')
SELECT * FROM [dbo].[fnResultListWithCondition] (’all')



Database Normalization


  1. Overview
  2. Anomaly
  3. Normalization
  •   First Normal Form (1NF)
  •  Second Normal Form (2NF)
  •  Third Normal Form (3NF)
  • Boyce Codd Normal Form (BCNF)
  1. Overview
            What is problem with that table?

The problem with above table is: Redundancy Data
And Data Redundancy will produce Anomaly
 
   2. What is Anomaly?
   Tables that have redundant data have problems known as anomalies. So data redundancy is cause of an anomaly.
   Redundancy is the duplication of the data.
   Type of anomalies
   There are 3 types of anomalies

  •     Insert Anomaly
  •     Delete Anomaly
  •     Update Anomaly

   Insert Anomaly
   An insert anomaly occurs when certain attribute cannot be inserted into the database without the presence of other attribute.














Delete Anomaly
   A delete anomaly exists when certain attributes are lost because of deletion of other attributes.

Update Anomaly
    An update anomaly exist when one or more instances of duplicated data is updated, but not all.

3.Normalization
  This is database design technique which organizes table in manner that reduces redundancy and dependency of data (That means avoid anomaly).
  Normalization is 'standardized' rule for make database.

First Normal Form (1NF)
 First Normal Form: No Repeating Elements or Groups of Elements

  • A row of data cannot contain repeating groups of similar data; and
  • Each row of data must have a unique identifier (or Primary Key).

Second Normal Form (2NF)
All requirements for 1NF must be met.
Redundant data across multiple rows of a table must be moved to a separated table.

Third Normal Form (3NF)

All requirements for 2NF must be met.
Eliminate fields that do not depend on the primary key.

Boyce Codd normal form (BCNF)
It is an advance version of 3NF that’s why it is also referred as 3.5NF. BCNF is stricter than 3NF. A table complies with BCNF if it is in 3NF and for every functional dependency X->Y, X should be the super key of the table.

Example: Suppose there is a company wherein employees work in more than one department.
They store the data like this: