表的主键编号要自动生成,可是应该如何生成才不会重复,并且不会随着使用时间的增长使得编号越来越大。郁闷了很久,没有想出一个很完美的办法,想来很多人都可能遇到这个问题,大家多讨论。另外讨论如何的编号方法能体现出树型结构?

解决方案 »

  1.   

    但是不希望太长的编号,有些只有3位,我用的是sybase 数据库
      

  2.   

    RK200407220001
    RK:类型
    200040722 当前日期 由DATE() 可得到
    0001 当日的号数,,每次取最大直就可以了,,,
      

  3.   

    我用SQL Sever2000数据库.
    首先定义一个变量recordID
    然后在添加记录代码中操作(移到最末记录):
          dataset1.last;
    读取最末一条记录ID号,给recordid,在添加记录操作时recordid+1,并把它传递给数据库中ID号。
    试试,我做过的,应该没问题。      
      

  4.   

    最好用sql procedure.  日期+0001转成字符,本人写一小例:
    create procedure datetoid
    @no varchar(12) output
    as
    declare @year,@month,@day
    set @year=year(getdate())
    set @month=month(getdate())
    set @day=day(getdate())
    set @no=''
    begin
    select @no=str(@year,4,0)+
                              (select case when @month>=10 then str(@month,2,0)
                                           when @month<10  then str(@month,1,0)
                                 end)+
                              (select case when @day>=10 then str(@day,2,0)
                                           when @day<10  then str(@day,1,0)
                                 end)
    end
      

  5.   

    function TdmDataModule.UniqueID(ATable, AField: string; AWidth: Integer): string;  function Copy9(Count: Integer): string;
      var
        I: Integer;
      begin
        Result := '';
        for I := 1 to Count do
          Result := Result + '9';
      end;  function Add0(Value: Int64; Len: Integer; B: Boolean): string;
      var
        I: Integer;
        S: string;
      begin
        S := IntToStr(Value);
        if Length(S) > Len then
        begin
          if B then
            Result := Copy(S, Length(S) - Len + 1, Len)
          else
            Result := S;
        end
        else
        begin
          for I := 1 to Len - Length(S) do
            S := '0' + S;
          Result := S;
        end;
      end;
      
    var
      cdsData: TClientDataSet;
      SQL, AId: string;
      vDatas: Variant;
    begin
      Result := '';
      Sql := 'SELECT MAX(' + AField + ') AS ' + AField + ' FROM ' + ATable;
      vDatas := GetData(Sql);
      if vDatas = NULL then Exit;
      cdsData := TClientDataSet.Create(nil);
      try
        with cdsData do
        begin
          Data := vDatas;
          if FieldValues['' + AField + ''] = NULL then
            Result := Add0(1, AWidth, True)
          else
          begin
            AId := FieldValues['' + AField + ''];
            if AId > Copy9(AWidth) then
            begin
              Result := '产生最大代码时出现错误,超过编码的最大范围。';
              FreeAndNil(cdsData);
              Exit;
            end
            else
              Result := Add0(StrToInt64(AId) + 1, AWidth, True);
          end;
        end;
      finally
        FreeAndNil(cdsData);
      end;
    end;