如何从sql中的字符串中删除某些字符?

问题描述 投票:0回答:5

我想从 SQL 中的字符串中删除所有特殊字符。我见过很多人使用子字符串方法来删除一定数量的字符,但在这种情况下,字符串每一侧的长度都是未知的。

有人知道该怎么做吗?

sql string varchar trim
5个回答
1
投票

使用

replace
功能会帮助你

我的意思是说,当您想删除特殊字符时,请使用替换功能替换此空格' '

有关替换的更多信息: http://technet.microsoft.com/en-us/library/ms186862.aspx


1
投票

在 MS SQL 中,这将删除所有加号:

SELECT REPLACE(theField, '+', '') FROM theTable

这是您需要的东西吗?


1
投票

我编写这个函数是为了向左修剪任何字符

CREATE FUNCTION TRIMCHAR
(
    -- Add the parameters for the function here
     @str varchar(200) ,  @chartotrim varchar(1)
)
RETURNS  varchar(200)  
AS
BEGIN



DECLARE @temp varchar(2000)

SET  @temp = @str   

WHILE  CHARINDEX (  @chartotrim  ,  @temp )  =1
BEGIN


SET @temp  = RIGHT( @temp , LEN(@temp)-1) 

END 


RETURN   @temp 

END
GO

0
投票
USE [YourDataBase]
GO
/****** Object:  UserDefinedFunction [Accounts].[fn_CurrentFeeorArrears]    Script Date: 02/18/2014 12:54:15 ******/
/*****Developed By rameez****/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [FN_REMOVE_SPECIAL_CHARACTER] 
(  
 @INPUT_STRING varchar(300))
RETURNS VARCHAR(300)
AS 
BEGIN

--declare @testString varchar(100),
DECLARE @NEWSTRING VARCHAR(100) 
-- set @teststring = '@ram?eez(ali)'
 SET @NEWSTRING = @INPUT_STRING ; 
With SPECIAL_CHARACTER as
(
--SELECT '>' as item
--UNION ALL 
--SELECT '<' as item
--UNION ALL 
--SELECT '(' as item
--UNION ALL 
--SELECT ')' as item
--UNION ALL 
--SELECT '!' as item
--UNION ALL 
--SELECT '?' as item
--UNION ALL 
--SELECT '@' as item
--UNION ALL 
--SELECT '*' as item
--UNION ALL 
--SELECT '%' as item
--UNION ALL 
SELECT '$' as item
 )
SELECT @NEWSTRING = Replace(@NEWSTRING, ITEM, '') FROM SPECIAL_CHARACTER  
return @NEWSTRING 
END
select dbo.[FN_REMOVE_SPECIAL_CHARACTER] ('r$@ameez')

0
投票

这仅适用于 SQL Server 2014 及之前的版本

CREATE FUNCTION [dbo].[RTrimCharacter]
(
@Value NVARCHAR(4000),
@CharacterToTrim NVARCHAR(1)
)

RETURNS NVARCHAR(4000)
AS
BEGIN

    -- define a temporary nvarchar
    declare @temp nvarchar(4000)
    
    -- copy the input
    set @temp = @Value

    -- rtrim it
    set @temp = RTRIM(@temp)

    while (@Value = @temp)

    begin

        -- set the original to temp
        set @Value = @temp

        -- trim it the last if the character
        if RIGHT(@temp, 1) = @CharacterToTrim
        set @temp  = LEFT( @temp , LEN(@temp)-1) 

        -- additionally trim the spaces
        set @temp = RTRIM(@temp)

    end

    RETURN @temp
END
© www.soinside.com 2019 - 2024. All rights reserved.