2013-08-02 28 views
2

我需要查詢表中的行,其中一列匹配的字符串的定義特徵是特定長度的字母數字字符串(例如4),後跟「:」由一個整數。在sql中對特定長度的字符串進行模式匹配

  • 模式:alphanumericstring:整數
  • 例1:1234:someint
  • 例2:ABCD:someotherint

我嘗試以下

select * from mytable where col1 like '[]{4}:%' 

select * from mytable where col1 like '.{4}:%' 

既不這些工作。我知道我甚至沒有試圖確保「:」後面的那個是一個整數。

+0

什麼SQL服務器的組合?許多支持正則表達式匹配。例如,在Postgresql中:'select * from mytable where col1〜'。{4}:[1-9] [0-9] +'' –

+1

@ David-SkyMesh:SQL Server中至今沒有對regex的支持;你必須通過CLR函數公開.NET功能來獲得 – OzrenTkalcecKrznaric

+0

@OzrenTkalčecKrznarić啊,我沒有看到'sql-server'標籤。 –

回答

1

您可以使用charindexsubstringisnumeric

CREATE TABLE MyTable 
(
    col1 varchar(20), 
    col2 varchar(50) 
) 

INSERT INTO MyTable 
    VALUES 
    ('ABCD:123', 'Value 123'), 
    ('1234:1234', 'Value 1234'), 
    ('xyz:1234', 'should not be selected'), 
    ('cdef:abcd', 'should not be selected too') 


SELECT * 
FROM MyTable 
WHERE CHARINDEX(':', col1, 0) = 5 AND 
     ISNUMERIC(SUBSTRING(col1, CHARINDEX(':', col1) + 1, 20)) = 1 
2

SQL Server不直接支持正則表達式(如果你四處搜索,你可能會找到一些教程來通過用戶定義的函數來添加它們)。

LIKE不支持量詞,但它具有通配符和輕量級字符類。

下劃線匹配任何字符:

SELECT col1 
FROM data 
WHERE col1 LIKE '____:%'; 

也可以指定字符的範圍(一個或多個)匹配:

SELECT col1 
FROM data 
WHERE col1 LIKE '[a-z0-9][a-z0-9][a-z0-9][a-z0-9]:%'; 

看到這些live on SQLFiddle

要指定第二部分必須包含的數字只,可以使用一個附加條件:

SELECT col1 
FROM data 
WHERE col1  LIKE '[a-z0-9][a-z0-9][a-z0-9][a-z0-9]:%' 
    AND col1 NOT LIKE '[a-z0-9][a-z0-9][a-z0-9][a-z0-9]:%[^0-9]%'; 

你可以test the last one live as well

+0

您的所有建議都適合我。感謝您向我介紹SQLFiddle。 – arunsun

0

這是醜陋的,但是這應該解決您的問題,爲正整數:

;WITH test AS (
    SELECT expr = '1234:3421' 
    UNION ALL SELECT '1234:25' 
    UNION ALL SELECT '1234:xx') 
select * 
from test 
where 
    expr like '%:[0-9]' 
    OR expr like '%:[0-9][0-9]' 
    OR expr like '%:[0-9][0-9]' 
    OR expr like '%:[0-9][0-9][0-9]' 
    OR expr like '%:[0-9][0-9][0-9][0-9]' 
    OR expr like '%:[0-9][0-9][0-9][0-9][0-9]' 
    OR expr like '%:[0-9][0-9][0-9][0-9][0-9][0-9]' 
    OR expr like '%:[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' 
    OR expr like '%:[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' 
    OR expr like '%:[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' 
    OR expr like '%:[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'