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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM