2010-09-13 156 views
2

問候, 我需要檢查值存儲數據庫的格式是否正確。它應該檢查類似的東西:如何檢查格式是否正確

x-x 
x-xx 
xx-xx 
xxx-xxx 
etc. 

其中xxx應該是一個整數。因此,概念是檢查值是否具有以下格式:整數 - 整數

回答

0

試試這個 -

select CASE WHEN (
charindex('-',columnName) > 0 
AND 
ISNUMERIC(left(columnName,(charindex('-',columnName)-1))) > 0 
AND 
ISNUMERIC(right(columnName,(charindex('-',columnName)))) > 0 
) THEN 1 ELSE 0 END as properWord 
from myTable 

返回1,如果合適的話否則返回0

編輯:作品假設你沒有與任何連續的字符串「 - 」喜歡「 - 」後面兩側的數字。適用於所有其他情況。

+1

不幸的是,-1是數字,所以這匹配'1--1' – Andomar 2010-09-13 10:05:42

+0

@Andormar - 啊..明白了。 – 2010-09-13 10:24:18

4

SQL沒有最強大的模式匹配。但是,這個查詢應該找到最糟糕的格式:

select * 
from YourTable 
where col1 like '%[^0-9-]%' 
     or col1 like '%-%-%' 
     or col1 not like '%[0-9]-[0-9]%' 

的工作方式就像:

  • col1 like '%[^0-9-]%'可能只有數字和連
  • col1 like '%-%-%'不能有兩個破折號
  • col1 not like '%[0-9]-[0-9]%'必有一成爲破折號左側和右側的數字
+0

有趣的是,你寫了一個查詢來查找不好的數據,但我寫了一個查找好數據。我猜,OP使用「check」工作使我想到了CHECK約束。 – Pondlife 2010-09-13 12:08:41

0
create table #t (
    txt varchar(100) 
) 
go 

insert into #t select '1-1' 
insert into #t select '11-22' 
insert into #t select '1-1-' 
insert into #t select '1-A' 
insert into #t select '1-A1' 
insert into #t select '-' 
insert into #t select '1-1-1' 
insert into #t select '1 - 3' 
go 

select 
    txt 
from 
    #t 
where 
    -- digits and dashes only 
    txt not like '%[^0-9-]%' and 
    -- one dash only 
    len(replace(txt, '-', '')) = len(txt)-1 and 
    -- starts and ends with a digit 
    txt like '[0-9]%[0-9]' 

應該這樣做,假設你沒有處理空間或任何其他的要求,你可以把它變成一個CHECK約束,如果你想要的。