过滤无效字符串的方法 ----------T-SQL

1.第一个方法

      

  1. CREATE FUNCTION [dbo].[RemoveNonAlphaCharacters](@Temp VARCHAR(1000))
  2. RETURNS VARCHAR(1000)
  3. AS
  4. BEGIN
  5.  
  6.     WHILE PATINDEX('%[^a-z]%', @Temp) > 0
  7.         SET @Temp = STUFF(@Temp, PATINDEX('%[^a-z]%', @Temp), 1, '')
  8.  
  9.     RETURN @TEmp
  10. END

2.第二个方法

  

  1. CREATE FUNCTION [dbo].[RemoveNonAlphaNumericCharacters](@Temp VARCHAR(1000))
  2. RETURNS VARCHAR(1000)
  3. AS
  4. BEGIN
  5.  
  6.     WHILE PATINDEX('%[^a-z^0-9]%', @Temp) > 0
  7.         SET @Temp = STUFF(@Temp, PATINDEX('%[^a-z^0-9]%', @Temp), 1, '')
  8.  
  9.     RETURN @TEmp
  10. END

3.第三个方法

  

 

  

  1. CREATE FUNCTION [dbo].[RemoveNonNumericCharacters](@Temp VARCHAR(1000))
  2. RETURNS VARCHAR(1000)
  3. AS
  4. BEGIN
  5.  
  6.     WHILE PATINDEX('%[^0-9]%', @Temp) > 0
  7.         SET @Temp = STUFF(@Temp, PATINDEX('%[^0-9]%', @Temp), 1, '')
  8.  
  9.     RETURN @TEmp
  10. END

As you can see, the real work is done by using the like comparison functionality of the PatIndex function.

'%[^a-z]%'
'%[^a-z0-9]%'
'%[^0-9]%'

It should be relatively simple to modify the previous functions to suit any sort of comparisons. You can use it to remove ranges of characters, or even for single characters (similar to the replace function).

For example, if you wanted to remove certain punctuation characters, but leave everything else, you could use '%[^.^,^-]%' (to remove dot, comma, and dash).

You can use the following code to test this functionality. It creates a table variable with some sample data. The query at the end returns the original data, and another column showing the output from the three functions presented here.

 

 

4.调用这些方法

  1. DECLARE @Test TABLE(DATA VARCHAR(100))
  2.  
  3. INSERT INTO @Test VALUES('(111) 222-3333')
  4. INSERT INTO @Test VALUES('111-222-3333')
  5. INSERT INTO @Test VALUES('111.222.3333')
  6. INSERT INTO @Test VALUES('(800) XXX-3333')
  7. INSERT INTO @Test VALUES('')
  8. INSERT INTO @Test VALUES(NULL)
  9.  
  10. SELECT  DATA,
  11.         dbo.RemoveNonAlphaCharacters(DATA) AS AlphaOnly,
  12.         dbo.RemoveNonAlphaNumericCharacters(DATA) AS AlphaNumericOnly,
  13.         dbo.RemoveNonNumericCharacters(DATA) AS NumericOnly
  14. FROM    @Test

5.产生的结果

    Data           AlphaOnly   AlphaNumericOnly NumericOnly
---------      ----------- ---------------- -----------
(111) 222-3333             1112223333       1112223333
111-222-3333               1112223333       1112223333
111.222.3333               1112223333       1112223333
(800) XXX-3333 XXX         800XXX3333       8003333

NULL           NULL        NULL             NULL

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值