查询从sql server中的字符串的开头和结尾删除非字母字符

时间:2012-06-07 07:04:02

标签: sql-server sql-server-2008

因为我的表行具有以非字母字符开头和结尾的数据,例如“。”,“;”,“,”等。我需要从字符串中删除它们。我怎样才能做到这一点 ?我使用like语句完成了这个,我需要搜索每个模式并过滤。还有其他更好的方法吗?

select lrno,free_text ,
(CASE 
 WHEN free_text LIKE ',%'   THEN SUBSTRING (free_text,2,len(free_text)-1)
 END) FREE_TEXT_TRIM
from vwLRClass3_FreeText 
ORDER BY PROPERTY_TEXT_VALUE

1 个答案:

答案 0 :(得分:0)

“下方”功能将从字符串中删除其他非字母字符。

IF object_id('dbo.GetAlphachars') is not NULL
   DROP FUNCTION dbo.GetNumeric 
GO

CREATE FUNCTION dbo.GetAlphachars (@strAlphachars VARCHAR(256)) 
RETURNS VARCHAR(256)
AS

BEGIN
DECLARE  @intAlpha INT
SET      @intAlpha = PATINDEX('%[^a-z]%', @strAlphachars )

BEGIN
WHILE    @intAlpha > 0
BEGIN
SET @strAlphachars  = STUFF(@strAlphachars, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^a-z]%', @strAlphachars )
END
END
RETURN ISNULL(@strAlphachars ,0)
END
GO

实施例

CREATE table vish(val varchar(20));

INSERT into vish values('.,,.?ishhh>...,');

SELECT dbo.getalphachars(val) from vish;

result
------------
ishhh