本函数可以将“目标字符串”以“指定字符串”进行拆分,并通过表结构返回结果。
在SQL Service中的代码如下:
1 CREATE FUNCTION [dbo].[fnSPLIT]
2 (
3 @sInputString varchar(8000)
4 , @sSplitChar varchar(10)
5 )RETURNS @tbl_List TABLE (SEQ INT IDENTITY(1,1),COD varchar(8000) )
6 AS
7
8 BEGIN
9 DECLARE @lInputStringLength Int ,
10 @lPosition Int ,
11 @lSplitChar Int
12
13 SET @lInputStringLength = LEN ( @sInputString )
14 SET @lPosition=1
15 SET @lSplitChar=1
16
17 WHILE @lPosition <= @lInputStringLength
18 BEGIN
19 SET @lSplitChar = CHARINDEX ( @sSplitChar , @sInputString , @lPosition)
20 IF @lSplitChar = 0
21 BEGIN
22 INSERT @tbl_List (COD )
23 SELECT SUBSTRING( @sInputString , @lPosition ,1+ @lInputStringLength - @lPosition)
24 SET @lPosition= @lInputStringLength + 1
25 END
26 ELSE
27 BEGIN
28 INSERT @tbl_List ( COD )
29 SELECT SUBSTRING( @sInputString , @lPosition , @lSplitChar - @lPosition)
30 SET @lPosition = @lSplitChar+1
31 END
32 END
33
34 DELETE @tbl_List WHERE RTRIM(COD)=''
35
36 RETURN
37 END
返回结果:
SELECT * FROM dbo.fnSPLIT('我的未来不是梦,我的心跟着希望在动',',')
在Oracle中的代码如下:
1 --在Type中的代码:
2 CREATE OR REPLACE TYPE str_split IS TABLE OF VARCHAR2 (4000);
3
4 --在Function中的代码:
5 CREATE OR REPLACE FUNCTION fnSPLIT
6 (
7 P_InputString IN VARCHAR2,
8 P_Flag IN VARCHAR2
9 )
10 RETURN str_split
11 PIPELINED
12 AS
13 v_length NUMBER := LENGTH(P_InputString);
14 v_start NUMBER := 1;
15 v_index NUMBER;
16 BEGIN
17 WHILE(v_start <= v_length)
18 LOOP
19 v_index := INSTR(P_InputString, P_Flag, v_start);
20
21 IF v_index = 0
22 THEN
23 PIPE ROW(SUBSTR(P_InputString, v_start));
24 v_start := v_length + 1;
25 ELSE
26 PIPE ROW(SUBSTR(P_InputString, v_start, v_index - v_start));
27 v_start := v_index + 1;
28 END IF;
29 END LOOP;
30
31 RETURN;
32 END fnSPLIT;
1 select * from (select rownum rn,t.* from table(fnSPLIT('我的未来不是梦,我的心跟着希望在动',',')) t)
将行转为列显示:
1 select a.column_value a,b.column_value b from
2 (select * from (select rownum column_id,t.* from table(fnSPLIT('我的未来不是梦,我的心跟着希望在动',',')) t)) a,
3 (select * from (select rownum column_id,t.* from table(fnSPLIT('我的未来不是梦,我的心跟着希望在动',',')) t)) b
4 where a.column_id=1 and b.column_id=2
如果您看了本篇博客,觉得对您有所收获,请点击右下角的
[推荐]如果您想转载本博客,
请注明出处如果您对本文有意见或者建议,欢迎留言
感谢您的阅读,请关注我的后续博客