2010-09-13 172 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约束,如果你想要的。