1. 程式人生 > >SqlServer 迴圈建表、刪除表、更新表

SqlServer 迴圈建表、刪除表、更新表

常用於分庫分表

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