博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在SQLServer2005下获取指定字段的某一区间的值

Posted on 2007-04-06 19:15  懒人ABC  阅读(1643)  评论(0编辑  收藏  举报

   在sqlserver里有substring()函数可以截取字符串,但是如果要截取指定的字节数,却不可以。
 找了一下,发现sqlserver2005下面有个datalength()函数可以计算出字节数,于是我用这个函数写了一个SubstringEx()函数用来截取字节数。
如果哪位朋友发现已有的函数可以调用或者更好的方法,请指出。鄙人的方法实在不敢恭维,见笑了。

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

-- =============================================
-- Author:  sicnco   
-- Create date: 2007/04/06 20:10
-- Description: substring by byte
-- =============================================
CREATE FUNCTION [dbo].[SubstringEx]
(
 -- Add the parameters for the function here
 @Text1 VARCHAR(255),  --The string which need to be changed
    @StartIndex int,                --The start of position
    @Offset int                        --The count of  bytes which want to be getted
)
RETURNS varchar(255)       --The string which want to be getted
AS
BEGIN
 -- Declare the return variable here
    declare @Index int 
    declare @Count1 int
    declare @Len int
    declare @Text2 varchar(255) --temp var string which want to be getted

    set @Count1 = 0;
    set @Len = len(@Text1)
    set @Text2  = @Text1;

    if (@Len < @StartIndex)
       return @Text2
   
 if (@StartIndex <= 0)
       return @Text2

    --if ((@StartIndex + @Offset - 1)  > @Len)
 --  return @Text2

    set @Text2 = ''

    set @Index = @StartIndex

    while (@Index <= 255)
    begin
      if datalength(substring(@Text1, @Index, 1)) = 1
           set @Count1 = @Count1 + 1
      else
           set @Count1 = @Count1 + 2

        if @Count1 <= @Offset AND @Index <= @Len
           begin
              set @Text2 = @Text2 + substring(@Text1, @Index, 1)
              set @Index = @Index + 1
              continue
           end
        else
           break
    end
    return @Text2
END