2017-02-22 106 views
0

信我将如何找到一个字符串的前四个字母只包含字母(大写或小写?)检查在字符串中的前导字符是使用SQL

我已经试过

  DECLARE @someString VARCHAR(40) = 'B331hBlahBlahBlah' 
      IF(SUBSTRING(@someString, 1, 4) LIKE '[A-Za-z]%') 
       print 'this is all text, no numbers in here' 
      else 
       print 'this string contains numbers' 

但输出是“这是所有的文字,在这里没有号码”

感谢所有帮助

+3

是这个SQL服务器? –

回答

2

您需要重复模式在每个人物:

 DECLARE @someString VARCHAR(40) = 'B331hBlahBlahBlah'; 

     IF @someString LIKE '[A-Za-z][A-Za-z][A-Za-z][A-Za-z]%') 
      PRINT 'this is all text, no numbers in here'; 
     ELSE 
      PRINT 'this string contains numbers'; 

您的版本仅测试第一个字符。其余的匹配通配符。

此外,substring()是不必要的通配符 - 一个或另一个,但都是矫枉过正。

更精确的再现 - 基于PRINT的消息 - 将是:

 DECLARE @someString VARCHAR(40) = 'B331hBlahBlahBlah'; 

     IF LEFT(@someString, 4) LIKE '%[0-9]%') 
      PRINT 'this string contains numbers'; 
     ELSE 
      PRINT 'this is all text, no numbers in here'; 
+0

这样做 - 感谢您的帮助! – Dough