[sql]Split2Table的function(split)

  • 5556
  • 0
  • 2012-07-19

摘要:[sql]Split2Table的function(split)


USE [Northwind]
GO
/****** Object:  UserDefinedFunction [dbo].[ufn_Split2Table]    Script Date: 06/22/2012 11:30:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		
-- Create date: <20120621>
-- Description:	<將傳進來的字串切割之後傳回table>
-- =============================================
ALTER FUNCTION [dbo].[ufn_Split2Table] 
(
	@input nvarchar(4000), --等待切割的字串(ex:30,80,77)
	@delimeter varchar(10) --分隔字員
)
RETURNS 
@tblReturn  TABLE (item1 nvarchar(60))
AS
BEGIN
	-- Fill the table variable with the rows for your result set
	DECLARE @pIndex smallint
	WHILE (@input<>'')
	BEGIN
		SET @pIndex = patindex('%'+@delimeter+'%', @input)
		IF @pIndex=0 SET @pIndex = len(@input) + 1
		--插入暫存table中
		INSERT INTO @tblReturn (item1)VALUES	(substring(@input, 1, @pIndex - 1))
		IF @pIndex=LEN(@input)+1 BREAK--表示已經沒有分隔字元了
		--將input中已經插入table的數字,刪除
		SET @input = substring(@input, @pIndex + 1, len(@input) - @pIndex)
	END

RETURN
END

使用方式如下:


DECLARE @tmp varchar(100)
DECLARE  cur  cursor for 
SELECT * from dbo.ufn_Split2Table('abc*777','*')
OPEN cur 
FETCH next from cur into @tmp
WHILE(@@fetch_status = 0) 
begin
	print (@tmp)
	fetch next from  cur into @tmp 
end 

參考網路神人文章

SQL_Split

改用patindex改寫而成,自己做個筆記

這個函數的中心精神就是一個一個目標抓出來然後insert到temp table,然後一個一個從原本的字串刪除