自定义函数分为二种,一种是标量值函数,另一种是表格值函数
1 标量值函数 :返回一个标量值
语法:
Create function 函数名(参数)
Returns 返回值数据类型
as
begin
SQL语句(必须有return 变量或值)
End
如示例:
CREATE FUNCTION MySTR(@strs VARCHAR(50))
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE @str2 VARCHAR(30)
SET @str2=@strs
RETURN @str2
END
--执行函数
SELECT dbo.MySTR('aa') AS result
在sql 语句也可以这样用:
DECLARE @str3 VARCHAR(30)
SET @str3=(select name from userinfo where huji=dbo.MySTR('邯郸') and id=23 )
select @str3
2 表格值函数 ,表格值函数有二种(内联表格值函数,多句表格值函数)‘
a 内联表格值函数
语法:
create function 函数名(参数)
returns table
as
return(一条SQL语句)
示例:
CREATE FUNCTION tabcmess(@title VARCHAR(10))
RETURNS TABLE
AS
return(select title,des from product where title like '%'+@title+'%')
--执行
SELECT * FROM tabcmess('aaa')
b、 多句表格值函数
create function 函数名(参数)
returns 表格变量名table (表格变量定义)
as
begin
SQL语句
end
示例:
CREATE function tabcmessalot (@title varchar(10))
Returns @ctable table(title varchar(10) null,des varchar(100) null)
As
Begin
Insert @ctable Select title,des from product WHERE title LIKE '%'+@title+'%'
return
End
--执行
SELECT * FROM tabcmessalot('aaa')
拆分函数
USE [XSMAN_DB]
GO
/****** Object: UserDefinedFunction [dbo].[func_SplitToTable] Script Date: 12/03/2012 23:25:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: cxy
-- Create date: 2010-10-28
-- Description: 根据分隔符分割字符串,返回表
-- =============================================
Create FUNCTION [dbo].[func_SplitToTable]
(
@SplitString nvarchar(max),
@Separator nvarchar(10)=' '
)
RETURNS @SplitStringsTable TABLE
(
[id] int identity(1,1),
[value] nvarchar(max)
)
AS
BEGIN
DECLARE @CurrentIndex int;
DECLARE @NextIndex int;
DECLARE @ReturnText nvarchar(max);
SELECT @CurrentIndex=1;
WHILE(@CurrentIndex<=len(@SplitString))
BEGIN
SELECT @NextIndex=charindex(@Separator,@SplitString,@CurrentIndex);
IF(@NextIndex=0 OR @NextIndex IS NULL)
SELECT @NextIndex=len(@SplitString)+1;
SELECT @ReturnText=substring(@SplitString,@CurrentIndex,@NextIndex-@CurrentIndex);
INSERT INTO @SplitStringsTable([value]) VALUES(@ReturnText);
SELECT @CurrentIndex=@NextIndex+1;
END
RETURN
END
--执行函数 1
select * from dbo.func_SplitToTable('1,2',',')
--执行函数 2
select * from dbo.func_SplitToTable('1-2-3','-')
--执行函数 3
select * from dbo.func_SplitToTable('1 2 3',' ')
获取Max行号:SELECT ISNULL(MAX(CAST(ISNULL(IIF(Number = '', NULL, Number ), 0) AS INT)), 0)+1 AS nummber FROM table
此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。