SQL数据字符串的拆分

一、概述:

MSSQL字符串的拆分没有封装太多常用的方式,所以如果向数据库中插入用特殊字符分割字符串(比如CB0$CB2$CB3,CB0$CB2$CB3)时就可能需要数据库能够分割字符串,SQL中拆分字符串的常用方法有

1、len(@strname) :查询字符串的长度

2、charindex('$',@strname,1) :查询特殊字符存在的位置index

3、substring(@strname,startindex,length):截取字符串长度

4、left(@strname,length):左边截取length字符

5、right(@strname,length):右边截取length字符

二、字符串动态拆分

现在完成一个查询,要求:动态输入格式CB1,CB2,CB3类似的字符串,字符串中间有个逗号分隔符,用字符串拆分,动态分割出所有组合字符串(逗号左右字符串);

实例1:

declare @PowerString nvarchar(200)  
set @PowerString='CB0$CB2$CB3,CB0$CB2$CB3'
declare @startindex int  
declare @endindex int  
declare @CurrResult nvarchar(50)  

set @startindex=1  
set @endindex=1  
while 1=1  
begin  
  set @endindex=charindex(',',@PowerString,@startindex);  
  if @endindex=0  
    set @endindex=LEN(@PowerString)+1  
  set @CurrResult=SUBSTRING(@PowerString,@startindex,@endindex-@startindex)  
  select @CurrResult
  set @startindex=@endindex+1   
  if @CurrResult is null or @CurrResult='' or @endindex=LEN(@PowerString)+1  
    break;   
end  

 实例二:一个存储过程,通过字符串拆分加上事务绑定,能够保证数据的完整性

Alter Proc p_HotelTour_Create  
 @HotelCode nvarchar(50),   
 @TouPics nvarchar(250),
 @resultcode int output  
as  
begin  
 declare @startindex int                
 declare @endindex int                
 declare @CurrResult nvarchar(50)             
 set @startindex=1                
 set @endindex=1   
 begin tran  
 begin try  
 --插入内容图片  
 while 1=1                
      begin                
   set @endindex=charindex('$',@TouPics,@startindex);                
   if @endindex=0                
   set @endindex=LEN(@TouPics)+1                
   set @CurrResult=SUBSTRING(@TouPics,@startindex,@endindex-@startindex)                         
   if not exists(select c_TourCode from HotelTour where c_HotelCode=@HotelCode and c_TourCode=@CurrResult)
        insert into HotelTour(c_HotelCode,c_TourCode,i_IsEnable) values(@HotelCode,@CurrResult,0)               
   set @startindex=@endindex+1                 
   if @CurrResult is null or @CurrResult='' or @endindex=LEN(@TouPics)+1                
   break;     
   end     
   commit tran 
   set @resultcode=1 
 end try  
 begin catch  
 rollback tran  
    set @resultcode=-1  
 end catch  
end
原文地址:https://www.cnblogs.com/xibei666/p/5230906.html