2017-02-22 108 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