這是一篇小備忘錄,在DB我通常會用一些自訂函數來解決一些事情,例如分割字串,在程式裡都有內建函式可以用,但SQL就沒有,所以建一個起來再寫T-SQL時會蠻方便的
Code :
USE [lenton]
GO
/****** Object: UserDefinedFunction [dbo].[Split] Script Date: 2014/1/16 下午 02:42:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Split]
(
@RowData varchar(8000),
@SplitOn nvarchar(1)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
沒有留言:
張貼留言