Portfoolio

SQL function

Funktsioonid

create procedure nimi
….
create function nimi
return ….
teeb mitu tegevus korragatagastab väärtused
–kutse
EXEC nimi;
EXECUTE nimi;
–kutse
SELECT veerunimi, funktsiooninimi
FROM tabelinimi
INPUT, OUTPUTINPUT
Protseduur – teeb tegevusi (muudab andmeid, käivitab mitmeid käske, ei pea väärtust tagastama)Funktsioon – arvutab midagi ja tagastab tulemuse, näiteks ühe väärtuse või tabeli.

Functionid:

--functionid
create table EmployeesWithDates
(
Id nvarchar(2),
Name nvarchar(20),
DateOfBirth datetime
)

INSERT INTO EmployeesWithDates  (Id, Name, DateOfBirth)  
VALUES (1, 'Dariia', '2007-07-07 08:40:06.031');
INSERT INTO EmployeesWithDates  (Id, Name, DateOfBirth)  
VALUES (2, 'Pam', '1982-09-01 12:02:36.260');
INSERT INTO EmployeesWithDates  (Id, Name, DateOfBirth)  
VALUES (3, 'John', '1985-08-22 12:03:30.370');
INSERT INTO EmployeesWithDates  (Id, Name, DateOfBirth)  
VALUES (4, 'Sara', '1979-11-29 12:59:30.670');

select * from EmployeesWithDates;
--- kuidas võtta ühest veerust andmeid ja selle abil luua uued veerud
--vaatab DoB veerust päeva ja kuvab päeva nimetuse sõnana
select Name, DateOfBirth, DATENAME(weekday, DateOfBirth) as [Day], 
--vaatab DoB veerust kp-d ja kuvab kuu nr
	MONTH(DateOfBirth) as MonthNumber,
-- vaatab DoB veerust kuud ja kuvab sõnana
	DateName(MONTH, DateOfBirth) as [MonthName],
-- v]tab Dob veerust aasta
	YEAR(DateOfBirth) as [Year]
from EmployeesWithDates

Tagastab:

Funktsiooni tegemine

create function fnComputeAge(@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)) + ' Years ' + cast(@months as nvarchar(2)) + 
		' Months ' + cast(@days as nvarchar(2)) + ' Days old'
	return @Age
end

Kuhu olemas ja mis näitab

select Id, Name, DateOfBirth, dbo.fnComputeAge(DateOfBirth)
as Age from EmployeesWithDates