SqlServer 循环建表、删除表、更新表

时间:2024-01-09 09:45:50

常用于分库分表

1、批量删除

declare @outter int
declare @inner int
declare @tablePrefix varchar(30)
declare @tableName varchar(36)
set @outter=1
set @inner=0
while (@outter<=12)
begin
set @tablePrefix='BankPayOrder_'+convert(varchar,@outter)+'_'
while(@inner<=9)
begin
set @tableName=@tablePrefix+convert(varchar,@inner)
execute('delete from '+@tableName+'')
set @inner=@inner+1
end
set @inner=0
set @outter=@outter+1
end

2、批量建表

declare @outter int
declare @inner int
declare @tablePrefix varchar(30)
declare @tableName varchar(36)
set @outter=1
set @inner=0
while (@outter<=12)
begin
set @tablePrefix='BankPayOrder_'+convert(varchar,@outter)+'_'
while(@inner<=9)
begin
set @tableName=@tablePrefix+convert(varchar,@inner)
execute('select * into '+@tableName+' from [BankPayOrderCommission_2018].[dbo].[BankPayOrder_1_0]')
set @inner=@inner+1
end
set @inner=0
set @outter=@outter+1
end