Sql server 自定义函数

今天修改以前写的分页存储过程的时候,需要对一个参数字符串值进行分割。想一想,要是在程序里多好实现呀。一个Split搞定。可这是SQL呀。。我也以为有这个函数,于是乎就翻开MSSQL的函数库。没个影子。只好自己实现了。记得函数,触发器,什么的。学校里都认识过,用过。没有自定义过。呵。现在工作中,大多用到表,存储过程,视图等。其它的很少用到。都忘记了。费话不多说了。 我们就利用SQL本身就有自带的函数来实现Split。

 

-- =============================================
-- Author:		Bndy
-- Create date: 2010-05-20
-- =============================================
CREATE FUNCTION [dbo].[Split]
(
	-- Add the parameters for the function here
	@sourceString nvarchar(4000),
	@separateChar char(1),
	@index int
)
RETURNS nvarchar(200)
AS
BEGIN
	declare @result nvarchar(200)
	declare @separateCharIndex int
	declare @cur bit
	declare @i int
	
	set @separateCharIndex = 1
	set @cur = 0
	set @i = 0
	set @result = @sourceString
	
	while @cur = 0
	begin
		set @separateCharIndex = charIndex(@separateChar, @result)
		if(@index <> @i)
			begin
				SET @result = Replace(@result, Substring(@result, 0, @separateCharIndex + 1),'')
			end
		else
			begin
				SET @cur = 1
				if(@separateCharIndex<>0)
					SET @result = Substring(@result, 0, @separateCharIndex)
				else
					SET @result = Substring(@result, 0, len(@result) + 1)
				break
			end
		
		set @i = @i + 1
	end

	-- Return the result of the function
	RETURN @result

END

示例:

 

 

print dbo.Split('Bndy.Net', '.', 0)
print dbo.Split('Bndy.Net', '.', 1)

Bndy
Net

 

posted @ 2010-05-20 19:39  bndy  阅读(393)  评论(0编辑  收藏  举报