2017-01-22 22 views
0

在Microsoft SQL Server Management Studio中我創建了一個用戶定義的函數基礎上誕生了用戶輸入的日期來計算僱員的年齡如下:需要在用戶定義的函數列,並將其存儲在一個過程中

USE [Northwind]; 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

CREATE FUNCTION udf_GetEmployeeAge_test2 
(
@DateOfBirth datetime 
) 
RETURNS int 
AS 
BEGIN 
DECLARE @Age int 
SELECT @Age = DATEDIFF(DAY, @DateOfBirth, GETDATE()) 
RETURN @Age 
END 

我使用的是流行的樣本Northwind數據庫,現在我似乎無法弄清楚的事情是如何和我在哪裏包括select語句返回每個員工的名字(名字),

姓(姓氏)​​,

出生日期(Bir thDate)

和age,然後還將Select語句包裝在存儲過程(usp_EmployeeAges)中。

這些列的信息是在表中稱爲dbo.Employees

+0

'選擇名字,姓,出生日期,年齡= dbo.udf_GetEmployeeAge_test2(出生日期)從yourtable'但年齡計算不正確 –

+0

使用此FLOOR((CAST(GetDate()AS INTEGER) - CAST(BirthDateAS INTEGER))/ 365.25)'來計算年齡。檢查這個問題[如何根據出生日期和getDate()]計算年齡(以年爲單位)(http://stackoverflow.com/questions/1572110/how-to-calculate-age-in-years-based-on -date-的出生和GETDATE) –

回答

0

通過切換到使用在線表值函數,而不是標量值的函數增加的性能。

而是與創建一個標量UDF的return條款,如:

return @Age 

與像return條款創建一個內聯表值UDF:

return select Age = <expression> 

在查詢中,代替:

age = dbo.udf_GetEmployeeAge(col1) 

用途:

age = (select age from dbo.udf_GetEmployeeAge(col1)) 

例聯表值UDF的年齡:

create function dbo.udf_GetEmployeeAge (@DateOfBirth datetime) 
    returns table as return 
    select Age = (convert(int,convert(char(8),getdate(),112)) 
       -convert(char(8),@DateOfBirth,112) 
       )/10000; 
go 

select * 
    , Age=(select Age from dbo.udf_GetEmployeeAge(Birth_Date)) 
    from pilots 

測試設置上rextester:http://rextester.com/CDAEI21728


要在存儲過程中使用它,你可以像查詢中一樣使用它。

create procedure dbo.get_Pilots_WithAge (@id int) as 
begin 
select * 
    , Age=(select Age from dbo.udf_GetEmployeeAge(Birth_Date)) 
    from pilots 
    where id = @id; 
end; 
go 

exec dbo.get_Pilots_WithAge @id=1; 

參考:

相關問題