发布:2022/12/22 14:04:52作者:管理员 来源:本站 浏览次数:593
IF OBJECT_ID(N'[dbo].[ufn_SplitToTable]', N'TF') IS NOT NULL
BEGIN
DROP FUNCTION [dbo].[ufn_SplitToTable];
END
GO
--==================================
-- 功能:分隔关键字字串集插入数据表
-- 作者: XXXX
-- 创建: XXXX-XX-XX
-- 修改: XXXX-XX-XX XX XXXXX
-- 调用:SELECT * FROM dbo.ufn_SplitToTable2('1|2|3','|')
--==================================
CREATE FUNCTION [dbo].[ufn_SplitToTable]
(
@chvnKeyWords NVARCHAR(4000), -- 要分隔的关键字字符串集
@chvnSeparator NCHAR(1) -- 要使用的分隔符,默认为'|'
) RETURNS @tblResult TABLE (
Num INT IDENTITY(1, 1) NOT NULL,
Word NVARCHAR(200) NOT NULL
)
--$Encode$--
AS
BEGIN
-- 分隔符参数为NULL时则使用"|"
SET @chvnSeparator = ISNULL(@chvnSeparator, N'|');
DECLARE @intPos AS INT = 0;
SET @intPos = CHARINDEX(@chvnSeparator, @chvnKeyWords);
WHILE @intPos >= 1 /* @intPos > 0*/
BEGIN
IF @intPos >= 2 /*@intPos > 1*/
BEGIN
INSERT INTO @tblResult (Word)
VALUES (LEFT(@chvnKeyWords, @intPos - 1));
END
-- 也可以使用SUBSTRING字符串函数
--SET @chvnKeyWords = SUBSTRING(@chvnKeyWords, @intPos + 1, LEN(@chvnKeyWords) - (@intPos + 1) + 1);
SET @chvnKeyWords = STUFF(@chvnKeyWords, 1, @intPos, N'');
SET @intPos = CHARINDEX(@chvnSeparator, @chvnKeyWords);
END
IF @chvnKeyWords > N''
BEGIN
INSERT INTO @tblResult (Word)
VALUES(@chvnKeyWords);
END
RETURN;
END
GO
执行以上代码后可直接使用ufn_SplitToTable函数
例:
select * from dbo.ufn_SplitToTable('180.255.88.250', '.')
执行结果:
180
255
88
250