我有以下SQL生成Insert语句,如下所示。
我的#order_ids表中总共有6854行,但我找不到将所有这些行包含在下面的insert语句中的方法。
插入内容总共会给我6355个ID。模数是500的批量,因为我有很多行,如果我要单独插入每个id,我的Insert语句将是巨大的。
虽然它可以或多或少,但它不必是500个批次,只要我们不是逐个插入表中。
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.
答案 0 :(得分:1)
这是一个工作(固定)的例子。第一次通过while
循环,@print
为NULL
,这意味着第一组500被跳过。所以你需要:
print 'insert into ...'
声明while
@print
初始化为非空值(例如id = 1
)@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')