2011年8月3日 星期三

[SQL] 純量值函數 SVF

 
這其實就很像C#裡的函式,從SQL Server 2005 開始都可以使用,
會傳回單一值,如字串、整數或位元值。

 這是計算2日期差的天數

在資料庫裡的 可程式性/函數/純量值函數 按右鍵就可以新增了


USE [DataBase]
GO
/****** Object:  UserDefinedFunction [dbo].[f_DatediffByDay]    Script Date: 08/03/2011 14:31:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
ALTER FUNCTION [dbo].[f_DatediffByDay]
(
-- Add the parameters for the function here
@Date1 nvarchar(20), @Date2 nvarchar(20)
)
RETURNS nvarchar(20)
AS
BEGIN
-- Return the result of the function
Return Convert(nvarchar(20), DateDiff(Day, Convert(DateTime,
Convert(Varchar(20), (Substring(@Date1, 0, Patindex('%/%', @Date1)) + 1911)) +
Convert(Varchar(20), Substring(@Date1, Patindex('%/%', @Date1), LEN(@Date1)))
 ),
 Convert(DateTime,
Convert(Varchar(20), (Substring(@Date2, 0, Patindex('%/%', @Date2)) + 1911)) +
Convert(Varchar(20), Substring(@Date2, Patindex('%/%', @Date2), LEN(@Date2)))
 )));
END
 

沒有留言:

張貼留言