我有两个数据表,A表中的id字段为主键,并且为自增1的int型数据,B表中b1字段用来记录A表中的id内容。
我在使用作业调度时,需要定时来实现把A表中的id字段内容插入至B表中,每天只插入一次。求一个高效的sql语句

解决方案 »

  1.   

    insert B(b1) select id from a where not exists ( select 1 from b where b1=a.id)
      

  2.   


    INSERT INTO [b]([b1])
    SELECT [id]
    FROM
    [A]
    WHERE
    [id]>(SELECT MAX([b1] FROM [b])
      

  3.   

    create table MaxID(MaxID int primary key)
    godeclare @Min int, @Max int
    select @Min = isnull(max(MaxID),0) + 1 from MaxID
    select @Max = ident_current('A表')
    insert B表 select id from A表 where id between @Min and @Max
    insert MaxID select @Max
    go
      

  4.   

    insert B(b1) select id from a where not exists ( select 1 from b where b1=a.id)
      

  5.   

    insert B(b1) select id from a where not exists ( select 1 from b where b1=a.id)为什么这个sql code执行了一次就不能再执行了?
      

  6.   

    create table MaxID(MaxID int primary key)
    godeclare @Min int, @Max int
    select @Min = isnull(max(MaxID),0) + 1 from MaxID
    select @Max = ident_current('A表')
    if @Max >= @Min
    begin
    insert B表 select id from A表 where id between @Min and @Max
    insert MaxID select @Max
    end
    go
      

  7.   

    create table MaxID(MaxID int primary key)
    godeclare @Min int, @Max int
    select @Min = isnull(max(MaxID),0) + 1 from MaxID
    select @Max = ident_current('A表')
    if @Max >= @Min
    begin
        insert B表 select id from A表 where id between @Min and @Max
        insert MaxID select @Max
    end
    go这个语句运行之后,如果需要循环运行,是否还需要drop table MaxID一下?
      

  8.   

    to Limpire :
    假如,我的B表中有ddate字段(varchar)、classid字段(int)
    ddate字段数据来源为select ddate=convert(varchar(10),getdate(),120)
    classid字段内容还是来源于A表的ID字段内容.
    请问这样的循环怎么写?
    为什么我写成
    create   table   MaxID(MaxID   int   primary   key) 
    go declare   @Min   int,   @Max   int 
    select   @Min   =   isnull(max(MaxID),0)   +   1   from   MaxID 
    select   @Max   =   ident_current('A表') 
    if   @Max   > =   @Min 
    begin 
            insert   B表(ddate,classid)   select ddate=convert(varchar(10),getdate(),120),select   id   from   A表   where   id   between   @Min   and   @Max 
            insert   MaxID   select   @Max 
    end 
    go drop table MaxID
    go
    是不正确的?
      

  9.   

    唉,还是用数据库的默认值方式解决了ddate字段问题。。多谢
      

  10.   

    /*
    我晕
    非要公仔画出肠才好看:
    */
    --手工创建一个表MaxID,保存每天A表的最大id,以下代码手工运行一次:
    create table MaxID(MaxID int primary key)
    declare @Max int
    select @Max = max(b1) from B表
    if @Max is null set @Max = ident_seed('A表') - 1
    insert into MaxID select @Max--以下代码在你的作业中运行:
    declare @Min int, @Max int
    select @Min = MaxID + 1 from MaxID
    select @Max = ident_current('A表')
    if @Max >= @Min
    begin
    insert B表 select id from A表 where id between @Min and @Max
    if @@rowcount > 0 update MaxID set MaxID = @Max
    end