From:http://www.cnblogs.com/for917157ever/archive/2012/12/03/2800591.html
自定義函數分為二種,一種是標量值函數,另一種是表格值函數
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',' ')
sql中實現split()功能參考:http://www.cnblogs.com/chengxiaohui/articles/2261243.html
獲取Max行號:SELECT ISNULL(MAX(CAST(ISNULL(IIF(Number = '', NULL, Number ), 0) AS INT)), 0)+1 AS nummber FROM table