本文將介紹Microsoft SQL Server
UDF的功能類似SQL Server中內建的系統函數
CREATE FUNCTION [ owner_name
( { { @parameter_name scalar_parameter_data_type
[
RETURN scalar_return_data_type
[WITH < function_option> [
[AS]
BEGIN
Function_body
RETURN scalar_expression
END
每個UDF可以帶有
函數體是UDF的主要部分
SCHEMABINDING是SQL Server
大家會注意到函數體以Begin開始
下面我用幾個例子來說明UDF的應用
Greatest and Least
為了區別於系統函數Max和Min
Case語句是兩個函數的核心
CASE WHEN value
雖然函數很簡單
CREATE FUNCTION dbo
(@Val
@Val
RETURNS SQL_VARIANT
AS
BEGIN
RETURN (CASE WHEN @val
END
go
―――――――――――――――――――――――――――――――
CREATE FUNCTION dbo
( @val
@val
RETURNS SQL_VARIANT
AS
BEGIN
RETURN (CASE WHEN @val
END
Go
大小寫轉換函數
該函數有兩個參數
依據 @Capitalize_What的值
¨ @Capitalize_What =
函數將 @string的第一個非空字符轉換成大寫
¨ @Capitalize_What =
函數將 @string中的每一句的首個非空字符轉換為大寫
¨ @Capitalize_What =
函數將 @string中的每個詞都轉換成首字符大寫
CREATE FUNCTION dbo
@String VARCHAR (
@Capitalize_What VARCHAR (
)
RETURNS VARCHAR(
AS
BEGIN
DECLARE @Position SMALLINT
@Char CHAR(
@First_Char CHAR (
@Word_Start SMALLINT
SET @Capitalize_What = LOWER( @Capitalize_What )
SET @Word_Start =
IF @Capitalize_What IN (
BEGIN
SET @Position = DATALENGTH( @String )
WHILE @Position >=
SET @Char = CASE @Position
WHEN
ELSE UPPER( SUBSTRING(
@String
END
IF @Char BETWEEN
OR @Char BETWEEN
SET @Word_Start = @Position
SET @First_Char = UPPER( @Char )
END
ELSE BEGIN
IF @Capitalize_What =
OR @Char in (
IF @Word_Start >
AND @First_Char BETWEEN
AND
SET @String = STUFF(
@String
SET @Word_Start =
END
END
SET @Position = @Position
END
END
ELSE BEGIN
SET @Position =
WHILE @Position < DATALENGTH( @String )
BEGIN
SET @Position = @Position +
SET @Char = UPPER( SUBSTRING( @String
@Position
IF @Char BETWEEN
OR @Char BETWEEN
SET @String = STUFF( @String
@Position
SET @Position =
END
END
END
RETURN( @String )
END
go
小結
SQL Server
UDF也有不足
在未來的版本中
CREAT FUNCTION dbo
( @parm int =
RETURN INT
AS
BEGIN
RETURN ( @parm )
END
UDF中諸如此類的小問題還有不少
From:http://tw.wingwit.com/Article/program/SQLServer/201311/22014.html