在 SQL 中修改模数

Modify Modulo in SQL

我有以下 SQL 生成插入语句,如下所示。

我的#order_ids table 中共有 6854 行,但是我找不到将所有这些行都包含到下面的插入语句中的方法。

Inserts 将给我总共 6355 个 ID。模以 500 为一批,因为我有很多行,如果我要单独插入每个 id,我的 Insert 语句会很大。

它不必以 500 个为一批,但可以或多或少,只要我们不一个一个地插入 table。

SQL查询

declare @total int, @current int, @print varchar(max)

select @total = COUNT(*) from #order_Ids 
set @current = 1

while @current <= @total
BEGIN
    IF @current % 500 = 0
    BEGIN 
        print @print
        print 'insert into #Orders_table values'
        select @print = value from #order_Ids where roworder = @current
    END
    ELSE
    BEGIN
        set @print = @print  + (select  ', ' + value from #order_Ids where roworder = @current)
    END
    set @current = @current + 1
END
print @print

想要的结果集

insert into #ORDER_IDS values
('ASC'), ('RFE'), ('ASW'), ('QWS'), ('ZAX'), ('LTY').........(500 VALUES IN TOTAL)
insert into #ORDER_IDS values
('YUR'), ('AWE'), ('VBN'), ('KIJ'), ('LOK'), ('PLP').........(500 VALUES IN TOTAL)
insert into #ORDER_IDS values
('BNV'), ('XCD'), ('GFG'), ('YHY'), ('IKI'), ('AAA')
insert into #ORDER_IDS values
ETC
UNTIL ALL 6854 VALUES ARE INCLUDED IN THE INSERT STATEMENTS. 

这是一个有效的(固定的)示例。第一次通过 while 循环 @printNULL,这意味着跳过了第一组 500。所以你需要:

  1. while 语句之前添加一个 print 'insert into ...'
  2. 在开始之前将 @print 初始化为非空值(如 where id = 1
  3. @current 开始于 2,因此您不会两次包含第一个值

这里是查询:

set nocount on

declare @data table (id int, val char(8))

insert into @data values
( 1, '(''ABC'')'), ( 2, '(''BCD'')'), ( 3, '(''CDE'')'), ( 4, '(''DEF'')'), ( 5, '(''EFG'')'),
( 6, '(''FGH'')'), ( 7, '(''GHI'')'), ( 8, '(''HIJ'')'), ( 9, '(''IJK'')'), (10, '(''JKL'')'),
(11, '(''KLM'')'), (12, '(''LMN'')'), (13, '(''MNO'')'), (14, '(''NOP'')'), (15, '(''OPQ'')'),
(16, '(''PQR'')'), (17, '(''QRS'')'), (18, '(''RST'')'), (19, '(''STU'')'), (20, '(''TUV'')'),
(21, '(''UVW'')'), (22, '(''VWX'')'), (23, '(''WXY'')'), (24, '(''XYZ'')')

declare @total int, @current int, @print varchar(max)

select @total = count(*) from @data
select @print = val from @data where id = 1
set @current = 2

print 'insert into #some_table values'
while @current <= @total
begin
  if @current % 3 = 0
  begin
    print @print
    print 'insert into #some_table values'
    select @print = val from @data where id = @current
  end
  else
  begin
    set @print = @print + (select ', ' + val from @data where id = @current)
  end
  set @current = @current + 1
end
print @print

这是输出:

insert into #some_table values
('ABC') , ('BCD') 
insert into #some_table values
('CDE') , ('DEF') , ('EFG') 
insert into #some_table values
('FGH') , ('GHI') , ('HIJ') 
insert into #some_table values
('IJK') , ('JKL') , ('KLM') 
insert into #some_table values
('LMN') , ('MNO') , ('NOP') 
insert into #some_table values
('OPQ') , ('PQR') , ('QRS') 
insert into #some_table values
('RST') , ('STU') , ('TUV') 
insert into #some_table values
('UVW') , ('VWX') , ('WXY') 
insert into #some_table values
('XYZ')