日期:2014-05-16 浏览次数:20712 次
--创建函数
create function [dbo].[f_splitstr](@SourceSql Nvarchar(MAX),@StrSeprate Nvarchar(100))
returns @temp table(F1 Nvarchar(100))
as
begin
declare @ch as Nvarchar(100)
set @SourceSql=@SourceSql+@StrSeprate
while(@SourceSql<>'')
begin
set @ch=left(@SourceSql,charindex(@StrSeprate,@SourceSql,1)-1)
insert @temp values(@ch)
set @SourceSql=stuff(@SourceSql,1,charindex(@StrSeprate,@SourceSql,1),'')
end
return
end
GO
--生成测试资料
IF EXISTS(SELECT NAME FROM sys.objects AS o WHERE o.name = 'test')
DROP TABLE test
GO
CREATE TABLE test(id INT IDENTITY(1,1) , book_name NVARCHAR(20))
GO
INSERT INTO test(book_name)
SELECT N'雷雨,安徒生童话,家' union all
SELECT N'家' union all
SELECT N'春;' union all
SELECT N'家;春;秋;'
GO
--执行查询
SELECT * FROM test AS t CROSS APPLY dbo.f_splitstr(replace(t.book_name , ',' , ';') , ';') AS fs WHERE FS.F1 <> ''
/*执行结果
id book_name F1
----------- -------------------- ----------------------------------------------------------------------------------------------------
1 雷雨,安徒生童话,家 雷雨
1 雷雨,安徒生童话,家