set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgo
ALTER function [dbo].[m_split](@c varchar(2000),@split varchar(2))
returns @t table(col varchar(200))
as
begin
while(charindex(@split,@c)<>0)
begin
insert @t(col) values (substring(@c,1,charindex(@split,@c)-1))
set @c = stuff(@c,1,charindex(@split,@c),‘‘)
end
insert @t(col) values (@c)
return
end
SQL 拆分字符串
标签:cti arch end val str 拆分 sql ble string
小编还为您整理了以下内容,可能对您也有帮助:
在SQL Server数据库中拆分字符串函数
SQL Server数据库中拆分字符串函数的具体方法
CREATE FUNCTION uf_StrSplit (@origStr varchar( ) 待拆分的字符串 @markStr varchar( )) 拆分标记 如 RETURNS @splittable table ( str_id varchar( ) NOT NULL 编号ID string varchar( ) NOT NULL 拆分后的字符串 ) AS BEGIN declare @strlen int @postion int @start int @sublen int @TEMPstr varchar( ) @TEMPid int SELECT @strlen=LEN(@origStr) @start= @sublen= @postion= @TEMPstr= @TEMPid= if(RIGHT(@origStr )<>@markStr ) begin set @origStr = @origStr + @markStr end WHILE((@postion<=@strlen) and (@postion != )) BEGIN IF(CHARINDEX(@markStr @origStr @postion)!= ) BEGIN SET @sublen=CHARINDEX(@markStr @origStr @postion) @postion; END ELSE BEGIN SET @sublen=@strlen @postion+ ; END IF(@postion<=@strlen) BEGIN SET @TEMPid=@TEMPid+ ; SET @TEMPstr=SUBSTRING(@origStr @postion @sublen); INSERT INTO @splittable(str_id string) values(@TEMPid @TEMPstr) IF(CHARINDEX(@markStr @origStr @postion)!= ) BEGIN SET @postion=CHARINDEX(@markStr @origStr @postion)+ END ELSE BEGIN SET @postion=@postion+ END END END RETURN END
例如 select * from uf_StrSplit( )
输出结果
lishixin/Article/program/SQLServer/201311/22421sql 如何将一个字段拆分成单个字符(如图:)
可以用substring函数来处理:
select substring(StyleID,1,1) as StyleID_1,substring(StyleID,2,1) as StyleID_2,substring(StyleID,3,1) as StyleID_3,substring(StyleID,4,1) as StyleID_4,substring(StyleID,5,1) as StyleID_5 from 表
SQL 如何把字符串拆分按固定值插入到表里?
--方法一(用xml来拆分字符串)
Select id,type,name,app From
(
Select id,type, CAST( '<v>'+REPLACE(name,',','</v><v>')+'</v>' as xml) As xml,app
From (select 1 As id,'A' As type,'张三,李四,王五' As name,0 As APP) S
) a outer apply ( Select x.y.value('.','varchar(100)') as name
From a.xml.nodes('/v') x(y)) b
--方法二(表值函数拆分字符串)
Create function f_split (@SourceSql varchar(8000),@StrSeprate varchar(2))
returns @temp table(col varchar(100))
as
begin
declare @ch as varchar(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
--调用
select 1 As id,'A' As Type,Col As name,0 As app
from dbo.f_split('张三,李四,王五',',')
sql语句进行字符串分割
substr(字符串,截取开始位置,截取长度) //返回截取的字
substr('Hello World',0,1) //返回结果为 'H' *从字符串第一个字符开始截取长度为1的字符串
substr('Hello World',1,1) //返回结果为 'H' *0和1都是表示截取的开始位置为第一个字符
substr('Hello World',2,4) //返回结果为 'ello'
substr('Hello World',-3,3)//返回结果为 'rld' *负数(-i)表示截取的开始位置为字符串右端向左数第i个字符