如何检查格式是否正确

时间:2010-09-13 08:54:22

标签: sql-server

问候, 我需要检查值存储数据库的格式是否正确。它应该检查类似的东西:

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

其中xxx应该是整数。因此,概念是检查值是否具有以下格式:整数 - 整数

3 个答案:

答案 0 :(得分: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]%'必须在短划线的左侧和右侧有一个数字

答案 1 :(得分: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
如果正确的其他字返回0,则

返回1

编辑:假设你没有连续' - '之类的字符串' - ',后跟两边的数字。适用于所有其他情况。

答案 2 :(得分: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约束。

相关问题