[T-SQL] Built-In Functions

Before we start to create our own functions let’s see what MS SQL has in the offer.

MATH

ROUND, FLOOR, CEILING

declare @Example1 table (Product Varchar(30), Price smallmoney)
insert into @Example1 (Product, Price)
values ('Ball1', 16.375), ('Ball2', 14.999), ('Ball3', 12.5), 
('Ball4', -15.13)

select Product, ROUND(Price, 1) as TotalAmount from @Example1

select Product, FLOOR(Price) as TotalAmount from @Example1

select Product, CEILING(Price) as TotalAmount from @Example1

MATH FUNCTIONS 1

SQRT, POWER

declare @Example4 table (Product Varchar(40), Size int)
insert into @Example4(Product, Size)
Values ('Ball', 9), ('Table', 64)

select Product, SQRT(Size) from @Example4
select Product, Power(Size,2) from @Example4
MATH FUNCTIONS 2.jpg

DATE

GETDATE, MONTH, YEAR, DAY

declare @Example2 table (Product Varchar(30), Price smallmoney, 
OrderDate date)
 insert into @Example2(Product, Price, OrderDate)
 values ('Ball1', 16.375, GETDATE()), ('Ball2', 14.999, 
GETDATE()), 
('Ball3', 12.5, GETDATE())

select Product, Price, MONTH(OrderDate) as MonthofDate 
from @Example2

select Product, Price, YEAR(OrderDate) as MonthofDate from 
@Example2

select Product, Price, DAY(OrderDate) as MonthofDate from 
@Example2

DATE FUNCTIONS 1.jpg

declare @Example3 table (Name Varchar(30), Position Varchar(50), 
Birthdate date)
 insert into @Example3(Name, Position, Birthdate)
 values ('Agnieszka', 'Prodcut Manager', '1989-12-12'), 
('Karol', 'Assistant', '1994-10-30'), 
('Bolesław', 'Warehouse Officer', '1988-03-12')

select Name, Birthdate,
 DATEDIFF ( yy , BirthDate , GETDATE() ) as Age
 from @Example3
MATH FUNCTIONS 2.jpg

TEXT

CAST, CONVERT, UPPER

SELECT Artist + ': ' + CAST (Album as varchar(100)) as FullInfo
FROM dbo.PRODUCTS

SELECT Artist + ': ' + Convert(varchar(100), Album, 1)
FROM dbo.PRODUCTS

SELECT Left(Artist,3) + ': ' + Convert(varchar(100), 
LEFT (Album,5), 1) as FullName
FROM dbo.PRODUCTS

SELECT Lower(Artist) + ': ' + Convert(varchar(100), 
LEFT (Album,10), 1) as FullName
FROM dbo.PRODUCTS

SELECT TOP 10 Upper(Condition) + ': ' + Convert(varchar(100), 
LEFT (Album,10), 1) + '/'+CAST(Artist as Varchar(5)) as FullName
FROM dbo.PRODUCTS
SIGN MULTIFUNCTIONS.jpg