如何判断一个字符串中含有非数字字符,我要求只能有0--9这十个数字,如何验证
一个字段设成字符型了,但是又要求只能录入数字,如何实现,
如何判断这个字符串中有非法字符呢?

解决方案 »

  1.   

    CHECK (col NOT LIKE '[^0-9]')
      

  2.   

    create table tb(col varchar(10))
    insert into tb values('aaa')
    insert into tb values('001')
    goselect * from tb where PATINDEX('%[^0-9]%',col) > 0drop table tb/*
    col        
    ---------- 
    aaa(所影响的行数为 1 行)
    */
      

  3.   

    declare @s varchar(50)
    set @s='54654546'
    if patindex('%[^0-9]%',@s)=0
    select '哦了'
    else
    select '只能0-9'
      

  4.   

    create function my function(@str)
    as
    begin
       declare @result int;
     
       declare @substr int;
       set @substr=@str;
       set @result =1; 
       while  len(@substr)>0
       begin
         if(ascii(left(@substr,1)) >=48 and ascii(left(@substr,1)) <=57 ) 
         begin
           @substr =right(@substr,len(@substr)-1);
         end
         else
         begin
           @result =0;
           break;
         end
       end
       if @result = 0 
       begin
        print "含有非数字字符" 
       end
       else
       begin
         print "不含有非数字字符"
       end 
    end
      

  5.   


    create table t (id varchar(5))
    insert into tb values('ww')
    insert into tb values('11')
    select * from t where patindex('%[^0-9]%',id)>0drop table t
      

  6.   


    create table tb (id varchar(5))
    insert into tb values('ww')
    insert into tb values('11')
    select * from tb where patindex('%[^0-9]%',id)>0drop table tb
    ww
      

  7.   


    create table tb(id varchar(5))
    insert into tb values('ww')
    insert into tb values('11')
    select * from tb  where isnumeric(id)=0
    drop table tb
      

  8.   


    create table tb(col varchar(10)) 
    insert into tb values('aaa') 
    insert into tb values('01aaa') 
    go select * from tb where PATINDEX('%[^0-9]%',col) > 0 drop table tb /*col        
    ---------- 
    aaa
    01aaa(所影响的行数为 2 行)*/
      

  9.   

    declare @m_str varchar(1024)select @m_str = '1234567890a1234567890'
    select patindex('%[^(0-9)]%',@m_str)
    -- 11select @m_str = '12345678901234567890'
    select patindex('%[^(0-9)]%',@m_str)
    -- 0
      

  10.   

    直接用isnumeric(字符串)来判断