Insert Into Customer1 (ID, CustomerName, City, Country) Values(103, 'Marwa','Baghdad','Iraq')

Similar documents
This course is aimed at those who need to extract information from a relational database system.

Reporting Functions & Operators

SQL SERVER DATE TIME FONKSİYON

Advanced SQL. Chapter 8 finally!

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Working with dates and times in SQL Server

Unit 1 - Chapter 4,5

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

DATABASE MANAGEMENT SYSTEMS

UNIT III INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL)

Senturus Analytics Connector. User Guide Cognos to Power BI Senturus, Inc. Page 1

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Prophet 21 World Wide User Group Webinars. Barry Hallman. SQL Queries & Views. (Part 2)

Every Byte Counts. Why Datatype Choices Matter. Andy Yun, Database Architect/Developer

SQL Data Definition Language: Create and Change the Database Ray Lockwood

Lab # 4. Data Definition Language (DDL)

SQL Server 2008 Tutorial 3: Database Creation

T- SQL Lab Exercises and Examples

Creating SQL Server Stored Procedures CDS Brownbag Series CDS

Senturus Analytics Connector. User Guide Cognos to Tableau Senturus, Inc. Page 1


Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

BEGINNING T-SQL. Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Cardkey Systems, Inc. Cardkey PEGASYS 1000 and 2000 MIS Interface Program 8K\OYOUT',KHX[GX_

Overview. Implementing Stored Procedures Creating Parameterized Stored Procedures Working With Execution Plans Handling Errors

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Full file at

Activant Solutions Inc. SQL 2005: Basic Data Manipulation

SQL Server Administration Class 4 of 4. Activant Prophet 21. Basic Data Manipulation

MySQL and MariaDB. March, Introduction 3

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Relational Database Language

Using DbVisualizer Variables

Structured Query Language

Advanced SQL Tribal Data Workshop Joe Nowinski

Downloaded from

Datatype-Related Problems, XML, and CLR UDTs

Stored Procedures and Functions. Rose-Hulman Institute of Technology Curt Clifton

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Index. Symbol function, 391

Lab # 2 Hands-On. DDL Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia

Chapter-14 SQL COMMANDS

Basic SQL. Basic SQL. Basic SQL

Exact Numeric Data Types

Database Management Systems,

SQL FUNCTIONS. Prepared By:Dr. Vipul Vekariya.

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

SQL Data Definition Language

Database Systems Laboratory 2 SQL Fundamentals

CS 327E Lecture 2. Shirley Cohen. January 27, 2016

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

1) Introduction to SQL

Programming and Database Fundamentals for Data Scientists

Unit 27 Web Server Scripting Extended Diploma in ICT

2.9 Table Creation. CREATE TABLE TableName ( AttrName AttrType, AttrName AttrType,... )

Data Base Lab. The Microsoft SQL Server Management Studio Part-3- By :Eng.Alaa I.Haniy.

Overview of MySQL Structure and Syntax [2]

Building Better. SQL Server Databases

Creating a Relational Database Using Microsoft SQL Code. Farrokh Alemi, Ph.D.

Honors Computer Science C++ Mr. Clausen Program 3A, 3B, 3C

ColdFusion Summit 2016

Chapter-8 DATA TYPES. Introduction. Variable:

What are temporary tables? When are they useful?

SAM Ad-Hoc. Gives direct, near unrestricted (view-only) access to your SAM database Ability to see raw data with queries created by you.

2 PL/SQL - fundamentals Variables and Constants Operators SQL in PL/SQL Control structures... 7

More MySQL ELEVEN Walkthrough examples Walkthrough 1: Bulk loading SESSION

Lecture 07. Spring 2018 Borough of Manhattan Community College

The Relational Model

user specifies what is wanted, not how to find it

SELF TEST. List the Capabilities of SQL SELECT Statements

SQL Server. Lecture3 Cascading referential integrity constraint

Simple Quesries in SQL & Table Creation and Data Manipulation

Module 8: Implementing Stored Procedures

Outline. Data and Operations. Data Types. Integral Types

SQL Commands & Mongo DB New Syllabus

7. Data Privacy Option for Oracle E-Business Suite

The Math Class. Using various math class methods. Formatting the values.

Microsoft Exam Querying Microsoft SQL Server 2012 Version: 13.0 [ Total Questions: 153 ]

Oracle 1Z MySQL 5.6 Developer.

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Integer Data Types. Data Type. Data Types. int, short int, long int

MySQL Workshop. Scott D. Anderson

Data Types in MySQL CSCU9Q5. MySQL. Data Types. Consequences of Data Types. Common Data Types. Storage size Character String Date and Time.

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

Phụ lục 2. Bởi: Khoa CNTT ĐHSP KT Hưng Yên. Returns the absolute value of a number.

MTAT Introduction to Databases

GlobAl EDITION. Database Concepts SEVENTH EDITION. David M. Kroenke David J. Auer

Deepak Bhinde PGT Comp. Sc.

DB2 Function Conversion for Sybase ASE Users

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

Basis Data Terapan. Yoannita

Some Basic Aggregate Functions FUNCTION OUTPUT The number of rows containing non-null values The maximum attribute value encountered in a given column

Practical 8. SHANKER SINH VAGHELA BAPU INSTITUTE OF TECHNOLGY Subject: - DBMS Branch: - IT/CE Semester: - 3rd. 1. What does SQL stand for?

Structure Query Language (SQL)

Transcription:

Insert Into Customer1 (ID, CustomerName, City, Country) Values(103, 'Marwa','Baghdad','Iraq')

Notes: 1. To View the list of all databases use the following command: Select * (or name) From Sys.databases

2. to view all tables in the current database we use: Select * From INFORMATION_SCHEMA.TABLES

Update Query The SQL UPDATE Query is used to modify the existing records in a table. You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be affected. The basic syntax of UPDATE query with WHERE clause is as follows: Update tablename Set columnname1=value1, columnname2=value2,..., columnnamen=valuen Where (Condition) You can combine N number of conditions using AND or OR operators.

Example: From the table Customer1 set the address value of (Marwa) as (Street-62).

Update Customer1 set [Address] = 'Street-62' Where ID=103 Now, Customer Hammed changes his postal code from 90110 to 698-325. Write a query to update the customers information?

Update Customer1 set postalcode = '698-325' Where ID=100

Notes: If we execute the query of update without using Where clause, all the records of this table will update that field with the new values. For example if we use the following query: Update Customer1 set postalcode = '698-325' All the postal code of the customers table will change into (698-325)

Delete Query The SQL DELETE Query is used to delete the existing record(s) from a table. You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted. The basic syntax of DELETE query with WHERE clause is as follows: Delete From table_name Where (condition) Be careful when we use Delete without Where clues.

Example: Tom is transferred to another department and this record must be deleted from the table, we use the following query

Delete From Customer1 Where ID=101

SQL - TRUNCATE TABLE COMMAND The SQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data. Syntax: Truncate Table table_name

SQL Server Lecture 9 Store Procedure Store Procedure With Input Parameter(s) Store Procedure With Output Parameter(s)

Store Procedure

A stored procedure is group of T-SQL (Transact SQL) statements. If you have a situation, where you write the same query over and over again, you can save that specific query as a stored procedure and call it just by it's name.

Create Store Procedure Let we have the following table: And we use the following command for the several time Select Name, Gender From Employee3

At this case for the batter using procedure. The general form of create procedure is: Create Procedure procedure_name as Begin statement(s) End OR Create Proc procedure_name as Begin statement(s) End

To create a procedure of the following statements: Select Name, Gender From Employee3 Create Proc spgetemployees as Begin Select Name, Gender From Employee3 End

How to execute procedure? 1. By text procedure name in SQL query: spgetemployees 2. By use the command EXEC or EXECUTE and then procedure name: EXEC spgetemployees OR EXECUTE spgetemployees 3. By use graphical mode

Store Procedure With Input Parameter(s)

This procedure is used when we have a parameter or parameters to input, for example at the pervious table we must inter the Gender and departmentid. For the other hand let say, we need to create a procedure that accepts Gender and DepartmentId. This SP, accepts GENDER and DEPARTMENTID parameters. Parameters and variables have an @ prefix in their name.

Create Proc spgetemployeesbygenderanddepartmentid @Gender nvarchar(10), @DepartmentId int as Begin Select Name, Gender, DepartmentId From Employee3 Where Gender = @Gender And DepartmentId = @DepartmentId End Now, to execute this procedure: spgetemployeesbygenderanddepartmentid 'Male',1

On the other hand, if you change the order, you will get an error stating "Error converting data type varchar to int." This is because, the value of "Male" is passed into @DepartmentId parameter. Since @DepartmentId is an integer, we get the type conversion error. When you specify the names of the parameters when executing the stored procedure the order doesn't matter. Exec spgetemployeesbygenderanddepartmentid @DepartmentId=2, @Gender='Female'

Note: All the methods of execute the store procedure without parameter(s) is available with parameters. When we execute the procedure with parameter(s), we must inter the value(s) of this parameters otherwise we get an error. Also in graphical method, we see the following windows that contains the parameter(s) that must enter the value(s) of it

Alter Procedure At the pervious example (spgetemployees) which procedure is: Create Proc spgetemployees as Begin Select Name, Gender, DepartmentId From Employee3 End After creation of this procedure, we need to sort the name, therefore at this case we must ALTER procedure as the following:

Alter Proc spgetemployees as Begin Select Name, Gender From Employee3 Order By Name End When we execute this procedure, we get: spgetemployees

How to view the text of the Store Procedure? To view the text, of the stored procedure Use system stored procedure sp_helptext 'SPName' sp_helptext spgetemployeesbygenderanddepartmentid

How to view the text of the Store Procedure? To view the text, of the stored procedure Use system stored procedure sp_helptext 'SPName sp_helptext spgetemployeesbygenderanddepartmentid Right Click the SP in Object explorer -> Scrip Procedure as -> Create To -> New Query Editor Window

Encrypt the text of the Store Procedure To encrypt the text of the SP, use WITH ENCRYPTION option. Once, encrypted, you cannot view the text of the procedure, using sp_helptext system stored procedure. There are ways to obtain the original text, which we will talk about in a later session. Alter Proc spgetemployees With Encryption as Begin Select Name, Gender From Employee3 Order By Name End

When we use the sp_helptext as the following: sp_helptext spgetemployees We get the message The text for object 'spgetemployees' is encrypted. Also when we use (Right Click the SP in Object explorer -> Scrip Procedure as -> Create To -> New Query Editor Window) we get:

Store Procedure With Output Parameter(s)

Stored procedures with output parameters To create an SP with output parameter, we use the keywords OUT or OUTPUT. @EmployeeCount is an OUTPUT parameter. Notice, it is specified with OUTPUT keyword.

Let we first create the following table(students): Create table Students ( Id int primary key identity(1,1), Name nvarchar(30) not null, Gender nvarchar(10), DepartmentId int )

Now, we need to crate the procedure that print a count of specify gender that entered by the user. The general form of creation a procedure with the output parameners is: Create Procedure spprocedurename @inputparameter1 datatype,... @outputparameter1 datatype OUTPUT,... as Begin......... End

Therefore, to create a procedure that specify an gender type (input) and out the count of this type(output), we use: Create Procedure spgetstudentscountbygender @Gender nvarchar(10), @StudentsCount int Output as Begin Select @StudentsCount=Count(Id) From Students Where Gender = @Gender End

Execute Store Procedure With Output Parameters After procedure creation, we must execute this procedure to view the result. To execute a store procedure with the output parameters: 1. First initialize a variable of the same datatype as that of the output parameter. We have declared @StudentsTotal integer variable. 2. Then pass the @StudentsTotal variable to the SP. You have to specify the OUTPUT keyword. If you don't specify the OUTPUT keyword, the variable will be NULL. 3. Execute

Declare @StudentsTotal int Execute spgetstudentscountbygender 'Male',@StudentsTotal Output Print @StudentsTotal The results of this procedure is: But if we execute the above procedure as the following: Declare @StudentsTotal int Execute spgetstudentscountbygender 'Male',@StudentsTotal Output The procedure is execute but without any value.

Notice that if not declare the output, or not use it in execute the error message will appear: Declare @StudentsTotal int Execute spgetstudentscountbygender 'Male' Print @StudentsTotal Msg 201, Level 16, State 4, Procedure spgetstudentscountbygender, Line 0 Procedure or function 'spgetstudentscountbygender' expects parameter '@StudentsCount', which was not supplied. Also, notice that if not specify @StudentsTotal as Output the result is a NULL Declare @StudentsTotal int Execute spgetstudentscountbygender 'Male', @StudentsTotal Print @StudentsTotal

IF Statement in Store Procedure The general form of using if statement is: If (Condition) Statement else Statemet Now, from pervious example, let we need to check @StudentsTotal if received a value or not by specify the OUTPUT key word or not.

At first let we execute the following: Declare @StudentsTotal int Execute spgetstudentscountbygender 'Male', @StudentsTotal Out If (@StudentsTotal is null) Print '@StudentTotal is NULL' Else Print '@StudentTotal is not NULL' The results is:

But when we execute the following: Declare @StudentsTotal int Execute spgetstudentscountbygender 'Male', @StudentsTotal If (@StudentsTotal is null) Print '@StudentTotal is NULL' Else Print '@StudentTotal is not NULL' The results is:

Note: If we use @StudentsTotal before @Gender in execute procedure what different should be made? Declare @StudentsTotal int Exec spgetstudentscountbygender @StudentsCount=@StudentsTotal Out, @Gender='Male' Print @studentstotal The output is:

Note; When we need information about one of the procedure that we creation we used (sp_help procedure_name), for example: sp_help spgetstudentscountbygender

Also, sp_help can use in any database object in sql server such as table, let we see what information we get if use the following command: sp_help Students

Note If we need to know that this procedure that creation what table that depends on it? We use sp_depends Procedure_Name, for example: sp_depends spgetstudentscountbygender

SQL Server Lecture 11 String Functions Date & Time

String Function

String Function: ASCII(Character_Expression): This function returns the ASCII code of the given character expression Example: Select ASCII('A'), ASCII('ABC'), ASCII('BC')

CHAR(Integer_Expression): Convert an integer ASCII code to character, the integer_expression should be from 0 to 255. Example: Select CHAR(65), CHAR(97)

Example: Declare @A1 int, @A2 int, @A3 int Set @A1=65 Set @A2=97 Set @A3=48 While(@A1<=90) Begin /*Select Char(@A1)*/ Print Char(@A1) Set @A1=@A1+1 End While(@A2<=122) Begin Print Char(@A2) Set @A2=@A2+1 End While(@A3<=57) Begin Print Char(@A3) Set @A3=@A3+1 End Print the character from (A-Z), (a-z), (0-9).

LTRIM(Character_Expression): Remove blanks on the left handside of the given character expression. RTRIM(Character_Expression): Remove blanks on the right handside of the given character expression For the example, let we have the following table:

We can use LTRIM as the following: Select Id, LTRIM(FirstName), LastName from Employee4

Also, we can use RTRIM: Select Id, RTRIM(FirstName), LastName from Employee4

Now, how we can get the following results? Select Id, LTRIM(RTRIM(FirstName))+' '+MiddleName+' '+LastName as FullName From Employee4

UPPER(Character_Expression): Convert all the character in the given character expression to the upper case letter. LOWER(Character_Expression): Convert all the character in the given character expression to the lower case letter. Example: if we need to view the pervious example(fullname) but FirstName in the UPPER case and LastName in LOWER case.

Select Id, UPPER(LTRIM(RTRIM(FirstName)))+' '+MiddleName+' '+LOWER(LastName) as FullName From Employee4

REVERSE(String_Expression): Reverse all the character in the given string expression LEN(String_Expression): Return the count of total character in the given string expression excluding the blank in the end of the expression. Example: View the FirstName in the Employee4 table in the reverse case and then calculate only the character of the FirstName (without blanks).

Select REVERSE(FirstName) as ReverseFirstName, LEN(LTRIM(FirstName)) as TotalCharLen From Employee4

Date and Time

Date & Time DataType in SQL Server There are some datatype that represent time and date and there are: Time: This type have the format hh:mm:ss.[nnnnnnn] with storage size from 3 to 5 bytes. Date: This type have the format YYYY-MM-DD with storage size 3 bytes. Smalldatetime: This type have the format YYYY-MM-DD hh:mm:ss with storage size 4 bytes. Datetime: This type have the format YYYY-MM-DD hh:mm:ss.[nnn] with storage size 8 bytes. Datetime2: This type have the format YYYY-MM-DD hh:mm:ss.[nnnnnnn] with storage size from 6 to 8 bytes. Datetimeoffset: this type have the format YYYY-MM-DD hh:mm:ss.[nnnnnnn] [+ -] hh:mm with storage size from 8 to 10 bytes.

Date and Time Functions There are many functions that get the time and date and there are represented by the table below:

Examples: Let to create the following table(tbldatetimetest): Create table tbldatetimetest ( [c_time] time, [c_date] date, [c_smalldatetime] smalldatetime, [c_datetime] datetime, [c_datetime2] datetime2, [c_datetimeoffset] datetimeoffset )

Now, let to insert the following to tbldatetimetest table: Insert into tbldatetimetest values (GETDATE(),GETDATE(),GETDATE(),GETDATE(),GETDATE(),GETDATE()) Then, we execute the following query Select * From tbldatetimetest The result is:

Now, how can set c_datetimeoffset with the current time zone (not +00:00)? Update tbldatetimetest set c_datetimeoffset=sysdatetimeoffset()

ISDATE: ISDATE( ): Checks if the given value, is valid date, time, or datetime, return (1) for success and (0) for failure. Example:

Select ISDATE('Pragin') Select ISDATE(GETDATE()) Select ISDATE('2016-01-02 11:43:59.637') Select ISDATE('2016-01-02 11:46:33.1441292') Note: For datatime2 values, ISDATE( ) return Zero

DAY, MONTH, YEAR DAY( ):Return the day number of the month of the given date. MONTH( ): Return the month number of the year of the given date. YEAR( ): Return the year number of the given date.

Example: Select DAY(GETDATE()) Select DAY('03-25-2012') Select MONTH(GETDATE()) SELECT MONTH('03-25-2012') Select YEAR(GETDATE()) Select YEAR('03-25-2012')

DATENAME( ) Function DATENAME(DatePart,date):Return a string that represents a part of the given date.

Example: Select DATENAME(DAY,'2016-01-02 12:28:21.2493947') Select DATENAME(WEEKDAY,'2016-01-02 12:28:21.2493947') Select DATENAME(WEEK,'2016-01-02 12:28:21.2493947') Select DATENAME(MONTH,'2016-01-02 12:28:21.2493947')

Example: Let we have the following table (Employee5) And we need to view the following table from above table:

Note: To create the table of example we must set the (DateOfBirth) as datetime data type Create Table Employee5 ( Id int primary key identity(1,1), Name nvarchar(30), DateOfBirith datetime ) The solution of this example is: Select Name, DateOfBirth, Datename(Weekday,DateOfBirth) as [Day], Month(DateOfBirth) as MonthNumber, Datename(Month,DateOfBirth) as MonthName, Year(DateOfBirth) as Year From Employee5

DATEPART Function DATEPART(DatePart, Date): Return an integer representing the specified DatePart. This function is similar to DATENAME( ) but DATENAME( ) return nvarchar while DATEPART( ) return an integer.

Example: Select DATENAME(WEEKDAY,'2016-01-02 21:56:38.7729078') Select DATEPART(WEEKDAY,'2016-01-02 21:56:38.7729078') Select DATENAME(MONTH,'2016-01-02 21:56:38.7729078') Select DATEPART(MONTH,'2016-01-02 21:56:38.7729078')

DATEADD Function DATEADD(DatePart, NumberToAdd, Date): Return the DateTime, after adding specified NumberToAdd, to the datepart specified of the given date.

Example: Select DATEADD(DAY, 20, '2012-08-20 19:45:31.793') Select DATEADD(DAY, -20, '2012-08-20 19:45:31.793') Select DATEADD(MONTH, 5, '2012-08-20 19:45:31.793') Select DATEADD(YEAR, -2, '2012-08-20 19:45:31.793')

DATEDIFF Function DATEDIFF(DatePart, StartDate, EndDate): Return the count of the specified datepart boundaries crossed between the specified startdate and enddate. Example: Select DATEDIFF(MONTH, '11-30-2005', '01-31-2006') Select DATEDIFF(DAY, '11-30-2005', '01-31-2006')

Example: Write a query to calculate the specify birthday in Year, Month, Day Form Example if the birthday of person is (01-29-1977) then the results must be view as:

Declare @DOB Datetime, @tempdate Datetime, @years int, @months int, @days int set @DOB='01-29-1977' Select @tempdate=@dob Select @years=datediff(year, @tempdate, Getdate())- case when (Month(@DOB)>Month(Getdate())) Or (Month(@DOB)=Month(Getdate()) And Day(@DOB)>Day(Getdate())) Then 1 Else 0 End Select @tempdate=dateadd(year, @years, @tempdate)

Select @months=datediff(month, @tempdate, Getdate())- case when (Day(@DOB)>Day(Getdate())) Then 1 else 0 End Select @tempdate=dateadd(month,@months,@tempdate) Select @days=datediff(day, @tempdate,getdate()) Select @Years as Years, @months as Months, @days as [Days]

Now, how to use this query as a function? To understand this question we remember Employee5 table: And we need to view the following table:

At first, create function is similar to create store procedure need a name a parameter that passing to the function At the above query, not need (set @DOB= 01-29-1977 ) but this variable is passing as a parameter to the function as: Create Function fncomputage(@dob DateTime) Returns nvarchar(50) as Begin Declare @tempdate Datetime, @years int, @months int, @days int.. End

Also the last Select statement not need (Select @Years as Years, @months as Months, @days as [Days]) but we must declare the output of the function as: Declare @Age nvarchar(50) Set @Age=cast(@years as nvarchar)+' Year '+cast(@months as nvarchar)+' Months '+cast(@days as nvarchar)+' Day Old' Return @Age

Create Function fncomputage(@dob DateTime) Returns nvarchar(50) as Begin Declare @tempdate Datetime, @years int, @months int, @days int Select @tempdate=@dob Select @years=datediff(year, @tempdate, Getdate())- case when (Month(@DOB)>Month(Getdate())) Or (Month(@DOB)=Month(Getdate()) And Day(@DOB)>Day(Getdate())) Then 1 Else 0 End Select @tempdate=dateadd(year, @years, @tempdate)

Select @months=datediff(month, @tempdate, Getdate())- case when (Day(@DOB)>Day(Getdate())) Then 1 else 0 End Select @tempdate=dateadd(month,@months,@tempdate) Select @days=datediff(day, @tempdate,getdate()) Declare @Age nvarchar(50) Set @Age=cast(@years as nvarchar(4))+' Year '+cast(@months as nvarchar(2))+' Months '+cast(@days as nvarchar(2))+' Day Old' Return @Age End

Now, how to use this function? Select dbo.fncomputage('01-29-1977') as Age Now, this function can used to view table which need in this example:

Select Id, Name, DateOfBirth, dbo.fncomputage(dateofbirth) as DOB From Employee5

SQL Server Lecture 12 Mathematical Function

Mathematical Function To see all mathematical function that available in SQL server:

ABS(NumericExpression): Return absolute (Positive) number. Select abs(-10.35) CEILING(NumericExpression): Returns the smallest integer value that greater than or equal to the value of the NumericExpression. FLOOR(Numeric Expression): Return the largest integer value that less than or equal to the value of the NumericExpression.

Example: Select CEILING (15.2) Select CEILING (15.6) Select CEILING (-15.2) Select FLOOR (-15.6) Select CEILING (-15.6) Select FLOOR (15.2) Select FLOOR (15.6) Select FLOOR (-15.2)

POWER(Expression, Power): Return power value of the specified expression to the specified power. Select POWER(2,3) SQUARE(Number): Returns the square of the given number. SQRT(Number): Return the square root of the given number. Select SQUARE(8) Select SQRT(81)

RAND(Seed_Value): Return a random float number between 0 and 1. Rand() function return difference random value at each time called if not supplied seed. Rand() function take an optional seed parameter. When a seed_value is supplied, the RAND( ) function always return the same value for the same seed.

Example: Select RAND() as [1], RAND() as [2], Rand() as [3] Select RAND(1) as [1], RAND(1) as [2], Rand(1) as [3] Select RAND(2) as [1], RAND(2) as [2], Rand(2) as [3]

Example: Print random 10 numbers from 0 to 10 Declare @Co as int Set @Co=1 While(@Co<=10) Begin Print(Floor(Rand()*100)) Set @Co=@Co+1 End

ROUND(NumericExpression, Length, [Function]): Rounds the given numeric_expression based on the given length. This function takes 3 parameters Numeric_Expression: is the number that we want to round. Length: parameter specifies the number of the digits that we want to round. If the length is a positive number, then the rounding is applied for the decimal part. If the length is negative number, then the rounding is applied to the number before decimal. The optional function parameter: is used to indicate rounding, or truncation operation. 0 indicate rounding (default). Non zero indicate truncation.

Example: Select Round(850.556, 2) Select Round(850.556, 2, 1) Select Round(850.556, 1) Select Round(850.556, 1, 1) Select Round(850.556, -2) Select Round(845.556, -2) Select Round(850.556, -1) Select Round(845.556, -1) Select Round(1942.22, -3) Select Round(1942.22, -2)