تابع یا function با مقدار بازگشتی از نوع جدول SQL
برای ایجاد تابعی که دارای مقدار بازگشتی از نوع جدول در پایگاه داده SQL Server باشد میتوانید از کد زیر استفاده فرمائید. در ابتدا جدولی ایجاد می نمائیم و یک سری رکورد در جدول درج می نماییم. کد ایجاد پایگاه داده و جدول و درج رکوردها به شرح ذیل می باشد:
CREATE DATABASE schooldb CREATE TABLE student ( id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, gender VARCHAR(50) NOT NULL, DOB datetime NOT NULL, total_score INT NOT NULL, ) INSERT INTO student VALUES (1, 'Jolly', 'Female', '12-JUN-1989', 500), (2, 'Jon', 'Male', '02-FEB-1974', 545), (3, 'Sara', 'Female', '07-MAR-1988', 600), (4, 'Laura', 'Female', '22-DEC-1981', 400), (5, 'Alan', 'Male', '29-JUL-1993', 500), (6, 'Kate', 'Female', '03-JAN-1985', 500), (7, 'Joseph', 'Male', '09-APR-1982', 643), (8, 'Mice', 'Male', '16-AUG-1974', 543), (9, 'Wise', 'Male', '11-NOV-1987', 499), (10, 'Elis', 'Female', '28-OCT-1990', 400);
تابع مورد نظر :
USE schooldb GO CREATE FUNCTION BornBefore ( @DOB AS DATETIME ) RETURNS TABLE AS RETURN SELECT * FROM student WHERE DOB < @DOB
نحوه استفاده:
USE schooldb; SELECT name, gender, DOB FROM dbo.BornBefore('1980-01-01', '1990-12-31') ORDER BY DOB
خروجی:
name |
gender |
DOB |
Laura |
Female |
1981-12-22 00:00:00.000 |
Joseph |
Male |
1982-04-09 00:00:00.000 |
Kate |
Female |
1985-01-03 00:00:00.000 |
Wise |
Male |
1987-11-11 00:00:00.000 |
Sara |
Female |
1988-03-07 00:00:00.000 |
Jolly |
Female |
1989-06-12 00:00:00.000 |
Elis |
Female |
1990-10-28 00:00:00.000 |
مثالی دیگر از توابع:
کد ایجاد جدول و درج رکورد در جدول:
USE schooldb CREATE TABLE teacher ( id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, gender VARCHAR(50) NOT NULL, DOB datetime NOT NULL, )
INSERT INTO teacher VALUES (1, 'Rick', 'Male', '05-APR-1965'), (2, 'Shack', 'Male', '03-JUN-1972'), (3, 'Zack', 'Male', '04-MAR-1969'), (4, 'Elis', 'Female', '28-NOV-1959'), (5, 'Mint', 'Female', '29-DEC-1971')
کد ایجاد متد:
USE schooldb GO CREATE FUNCTION GetBornBetween ( @YearAfter AS DATETIME, @YearBefore AS DATETIME ) RETURNS @People TABLE ( Name VARCHAR (MAX), Gender VARCHAR(MAX), DOB DATETIME, Job VARCHAR(10) ) AS BEGIN INSERT INTO @People SELECT name, gender, DOB, 'student' FROM student WHERE DOB BETWEEN @YearAfter AND @YearBefore INSERT INTO @People SELECT name, gender, DOB, 'teacher' FROM teacher WHERE DOB BETWEEN @YearAfter AND @YearBefore RETURN END
نحوه استفاده از متد:
USE schooldb; SELECT * FROM dbo.GetBornBetween('1960-01-01', '1985-12-31')
خروجی:
Name |
Gender |
DOB |
Job |
Jon |
Male |
1974-02-02 00:00:00.000 |
student |
Laura |
Female |
1981-12-22 00:00:00.000 |
student |
Kate |
Female |
1985-01-03 00:00:00.000 |
student |
Joseph |
Male |
1982-04-09 00:00:00.000 |
student |
Mice |
Male |
1974-08-16 00:00:00.000 |
student |
Rick |
Male |
1965-04-05 00:00:00.000 |
teacher |
Shack |
Male |
1972-06-03 00:00:00.000 |
teacher |
Zack |
Male |
1969-03-04 00:00:00.000 |
teacher |
Mint |
Female |
1971-12-29 00:00:00.000 |
teacher |