现在的位置: 首页 > 综合 > 正文

数据库截取一定长度的字符串

2012年08月13日 ⁄ 综合 ⁄ 共 1477字 ⁄ 字号 评论关闭
数据库截取一定长度的字符串:

/*******************************************

    作者:小朱
    功能:获取一定长度的字符串
    日期:2004年11月01日

******************************************
*/

CREATE FUNCTION [dbo].[uf_GetString]
    (
        
@str VarChar(2000= '',    --要截取的字符串
        @getLen Int = 0            --要截取的长度,按中文的汉字计算
    )  
    
RETURNS VarChar(2000AS  
BEGIN 
    
Declare @lastStr VarChar(2000)
    
Declare @tempStr VarChar(2000)
    
Declare @str1 VarChar(2)
    
Declare @pos Int
    
Declare @ChineseCount Int
    
Declare @EnglishCount Int
    
Select @ChineseCount = 0
    
Select @EnglishCount = 0
    
Select @pos = 1
    
Select @tempStr = LTrim(RTrim(@str))
    
While @EnglishCount / 2 + @ChineseCount < @getLen
    
Begin
        
If Len(@tempStr< @getLen  OR @pos + 1 > Len(@tempStr
        
Begin
            
Select @lastStr = @tempStr
            
Break
        
End
        
Else
        
Begin
            
Select @str1 = SubString(@tempStr,@pos,1)
            
If DataLength(@str1= Len(@str1)
                
Select @EnglishCount = @EnglishCount + 1
            
Else
                
Select @ChineseCount = @ChineseCount + 1
            
            
If @EnglishCount / 2 + @ChineseCount >= @getLen
            
Begin
                
If @EnglishCount % 2 <> 0
                    
Select @lastStr = SubString(@tempStr,1,@pos -1+ ''
                
Else
                    
Select @lastStr = SubString(@tempStr,1,@pos+ ''
                
Break
            
End
            
Select @pos = @pos + 1
        
End
    
End
    
Return @lastStr 
END

抱歉!评论已关闭.