Modify Modulo in SQL -
i have following sql generates insert statements shown below.
i have total of 6854 rows in #order_ids table, cannot find way include of them insert statements below.
the inserts give me total of 6355 total ids. modulo in batches of 500, since have lot of rows, , insert statement huge if insert each id individually.
it doesn't have in batches of 500 though can more or less, long not inserting table 1 one.
sql query
declare @total int, @current int, @print varchar(max) select @total = count(*) #order_ids set @current = 1 while @current <= @total begin if @current % 500 = 0 begin print @print print 'insert #orders_table values' select @print = value #order_ids roworder = @current end else begin set @print = @print + (select ', ' + value #order_ids roworder = @current) end set @current = @current + 1 end print @print
desired result set
insert #order_ids values ('asc'), ('rfe'), ('asw'), ('qws'), ('zax'), ('lty').........(500 values in total) insert #order_ids values ('yur'), ('awe'), ('vbn'), ('kij'), ('lok'), ('plp').........(500 values in total) insert #order_ids values ('bnv'), ('xcd'), ('gfg'), ('yhy'), ('iki'), ('aaa') insert #order_ids values etc until 6854 values included in insert statements.
here working (fixed) example. first pass through while
loop, @print
null
, means first set of 500 skipped. need to:
- add
print 'insert ...'
beforewhile
statement - initialize
@print
non-null value before start (likeid = 1
) - start
@current
@2
, don't include first value twice
here query:
set nocount on declare @data table (id int, val char(8)) insert @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(*) @data select @print = val @data id = 1 set @current = 2 print 'insert #some_table values' while @current <= @total begin if @current % 3 = 0 begin print @print print 'insert #some_table values' select @print = val @data id = @current end else begin set @print = @print + (select ', ' + val @data id = @current) end set @current = @current + 1 end print @print
here output:
insert #some_table values ('abc') , ('bcd') insert #some_table values ('cde') , ('def') , ('efg') insert #some_table values ('fgh') , ('ghi') , ('hij') insert #some_table values ('ijk') , ('jkl') , ('klm') insert #some_table values ('lmn') , ('mno') , ('nop') insert #some_table values ('opq') , ('pqr') , ('qrs') insert #some_table values ('rst') , ('stu') , ('tuv') insert #some_table values ('uvw') , ('vwx') , ('wxy') insert #some_table values ('xyz')
Comments
Post a Comment