想插入name的时候首先检测需要输入属于哪个组,得到max(ID),然后max(ID)+1,输入name之后,保存。但是由于ID是VARchar类型,我无法实现max(ID)+1.我是新手,大家多多指教。谢谢
ID        name
a-001      t
a-002      d
b-001      a
b-002      s
b-003      g
c-001      h

解决方案 »

  1.   

    估计又要用到row_number() over(partition by sn order by sn )这玩易了。我刚刚还在想这语句怎么运用,老D来解答下吧。
      

  2.   

    那ID前面的a,b,c 怎么來的?有什麽規律?
      

  3.   

    create table tb(ID varchar(10), name varchar(10))
    insert into tb values('a-001' , 't') 
    insert into tb values('a-002' , 'd') 
    insert into tb values('b-001' , 'a') 
    insert into tb values('b-002' , 's') 
    insert into tb values('b-003' , 'g') 
    insert into tb values('c-001' , 'h')
    godeclare @id as varchar(10) 
    declare @maxid as varchar(10) 
    set @id = 'a'
    set @maxid = nullset @maxid = (select max(id) from tb where left(id,charindex('-',id)-1) = @id)if @maxid is null
       set @maxid = @id + '-001'
    else
       set @maxid = @id + '-' + right('00'+cast(cast(substring(@maxid , charindex('-',@maxid) + 1 , len(@maxid)) as int) + 1 as varchar),3)print @maxid/*
    a-003
    */drop table tb
      

  4.   

    想插入name的时候首先检测需要输入属于哪个组===》 怎么檢測?有邏輯嗎?
      

  5.   

    create table tb
    (
    id nvarchar(5),
    name nvarchar(50)
    )insert tb select 'a-001','t'
    insert tb select 'a-002','d' 
    insert tb select 'b-001','a' 
    insert tb select 'b-002','s' 
    insert tb select 'b-003','g' 
    insert tb select 'c-001','h' 
    DECLARE @idm NVARCHAR(3),@type NVARCHAR(1)
    SELECT @idm = '001',@type = 'a'
    WHILE EXISTS (SELECT * FROM tb WHERE right(id,3)=@idm and id like @type+'%')
    SELECT @idm=REPLICATE('0',3-LEN(CAST(CAST(@idm AS int)+1 AS varchar)))+CAST(CAST(@idm AS int)+1 AS varchar)
    select @type+'-'+@idmdrop table tb-----
    a-003
      

  6.   

    select max(id) from table where left(id,1)='a',这样检测啊,得到max(id)之后就max(id)+1,然后插入name,保存id与name。这样检测行不行啊?我这个菜鸟也真的很菜,所以请大家多多指教啊
      

  7.   

    select right(1000+right(max(id),3)+1,3) from [Table] where left(id,1)='a'
      

  8.   

    chuifengde,请问你这个right(1000+right(max(id),3)+1,3))什么意思啊,我知道right(max(id),3)是max(id)取右3位,然后加1,然后为什么会有(1000+right(max(id),3)+1)得出的结果是什么啊?里边是怎么运算的呢?我老想不明白
      

  9.   

    你可以找下规律,001->2->1002->002
      

  10.   

    为什么非要这样加?晕~~~~既然(1000+001+1)成立,为什么就不可以直接使用(right(max(id),3)+1)呢,即(001+1=002)?回答了我这个我就结贴啊,谢谢你们啊
      

  11.   

    '001'+1 内部有一个隐式转换,都换成int来计算,得到的结果为2,而要变成002,所以+1000=1002,1002是可以隐式转换为字符串用right来取后三位的