SQL里面用自定義Split()完成個性化需求
更新時間:2013年02月21日 15:06:14 作者:
為了滿足需求自定義Split()在SQL中實現(xiàn),代碼很整潔,感興趣的朋友可以參考下,或許對你學(xué)習(xí)sql語句有所幫助
復(fù)制代碼 代碼如下:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[SplitString]
(
@Input nvarchar(max),
@Separator nvarchar(max)=',',
@RemoveEmptyEntries bit=1
)
returns @TABLE table
(
[Id] int identity(1,1),
[Value] nvarchar(max)
)
as
begin
declare @Index int, @Entry nvarchar(max)
set @Index = charindex(@Separator,@Input)
while (@Index>0)
begin
set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1)))
if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
begin
insert into @TABLE([Value]) Values(@Entry)
end
set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input))
set @Index = charindex(@Separator, @Input)
end
set @Entry=ltrim(rtrim(@Input))
if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'')
begin
insert into @TABLE([Value]) Values(@Entry)
end
return
end
函數(shù)、表都建好了,下面調(diào)用測試一下吧:
復(fù)制代碼 代碼如下:
declare @str1 varchar(max), @str2 varchar(max), @str3 varchar(max)
set @str1 = '1,2,3'
set @str2 = '1###2###3'
set @str3 = '1###2###3###'
select [Value] from [dbo].[SplitString](@str1, ',', 1)
select [Value] from [dbo].[SplitString](@str2, '###', 1)
select [Value] from [dbo].[SplitString](@str3, '###', 0)
結(jié)果,截個圖來看一下:

相關(guān)文章
SQL集合函數(shù)中case when then 使用技巧
我們都知道SQL中適用case when then來轉(zhuǎn)化數(shù)據(jù)庫中的信息 比如 select (case sex when 0 then '男' else '女' end) AS sex from studentInfo2011-09-09SQL?Server事務(wù)日志文件過大(已滿)的解決方案
隨著數(shù)據(jù)庫使用時間增長,日志文件也在不停的增大,這篇文章主要給大家介紹了關(guān)于SQL?Server事務(wù)日志文件過大(已滿)的解決方案,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-10-10hive中將string數(shù)據(jù)轉(zhuǎn)為bigint的操作
這篇文章主要介紹了hive中將string數(shù)據(jù)轉(zhuǎn)為bigint的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09sqlserver 禁用觸發(fā)器和啟用觸發(fā)器的語句
sqlserver 禁用觸發(fā)器和啟用觸發(fā)器的語句,有需要的朋友可以試試。2009-09-09SqlServer數(shù)據(jù)庫提示 “tempdb” 的日志已滿 問題解決方案
本文主要講述了筆者在執(zhí)行sql語句的過程中,遇到提示“數(shù)據(jù)庫 'tempdb' 的日志已滿。請備份該數(shù)據(jù)庫的事務(wù)日志以釋放一些日志空間?!钡慕鉀Q過程,希望對大家有所幫助2014-08-08SQL?Server2019安裝的詳細(xì)步驟實戰(zhàn)記錄(親測可用)
SQL Server 2019作為編程人員必須使用到的一款數(shù)據(jù)庫管理軟件,許多初學(xué)者在安裝這款軟件的時候都出現(xiàn)了各種各樣的問題,下面這篇文章主要給大家介紹了關(guān)于SQL?Server2019安裝的詳細(xì)步驟,需要的朋友可以參考下2022-06-06Sqlserver timestamp數(shù)據(jù)類使用介紹
SQL Server timestamp 數(shù)據(jù)類型與時間和日期無關(guān)。SQL Server timestamp 是二進制數(shù)字,它表明數(shù)據(jù)庫中數(shù)據(jù)修改發(fā)生的相對順序。2011-08-08