如何将db2 TRIM函数转换为SQL Server

时间:2017-08-07 02:46:28

标签: sql sql-server

在db2数据库中:

select trim(T '0' from '00a0Bjifea00a000') 
from sysibm.sysdummy1;

我可以得到结果:00a0Bjifea00a

但是如何在SQL Server数据库中获得相同的结果呢?

2 个答案:

答案 0 :(得分:3)

我能想到的最好的函数可能是这样的[source],它将支持DB2功能:

CREATE FUNCTION dbo.DB2Trim
(
    @Side NVARCHAR(10),
    @CharacterToTrim NVARCHAR(1),
    @Value NVARCHAR(4000)

)
RETURNS NVARCHAR(4000)
AS
BEGIN
    IF (UPPER(@Side) IN ('L','B','','LEADING','LEFT','BOTH'))
        SET @Value = REVERSE(SUBSTRING(@Value, PATINDEX('%[^'+@CharacterToTrim+']%', @Value), LEN(@Value)));
    ELSE
        SET @Value = REVERSE(@Value);
    IF (UPPER(@Side) IN ('T','R','B','','TRAILING','RIGHT','BOTH')) 
        SET @Value = REVERSE(SUBSTRING(@Value, PATINDEX('%[^'+@CharacterToTrim+']%', @Value), LEN(@Value)));
    ELSE
        SET @Value = REVERSE(@Value);
    RETURN @Value
END
GO

用法:

SELECT dbo.DB2Trim('T','0', '00a0Bjifea00a000');

答案 1 :(得分:0)

CREATE FUNCTION [dbo].[TRIM_T](@STR1  NVARCHAR(MAX),@STR2  NVARCHAR(MAX))
returns  NVARCHAR(MAX)
AS
BEGIN
    DECLARE @len1  int
    DECLARE @len2 int
    DECLARE @start  int 

    IF isnull(@STR2,'')='' 
     begin 
     RETURN  @STR2
     end  
    set @len1=LEN(@STR1)
    set @len2=LEN(@STR2)
    IF @len2<@len1  
     BEGIN
      RETURN @STR2
     END 

    WHILE RIGHT(@STR2,@len1)=@STR1
    BEGIN
      set @STR2=STUFF(@STR2,LEN(@STR2)-@len1+1,@len1,'')
      set @len2=@len2-@len1
    END
    RETURN  @STR2
END

SELECT [dbo].[TRIM_T]('0','00a0Bjifea00a000')