表名作为变量的应用

--需求:一组表(假如有20个)中,每个表都有goodsno字段,如果这20个表的goodsno都不含值b,那么就将这20个表的goodsno值为a的记录的goodsno值修改为b


---------------------第一步:begin----------------------
IF OBJECT_ID('tempdb..#tablenames') IS NOT NULL
DROP TABLE #tablenames
select '#tbname1' tbname into #tablenames
union all select '#tbname2'
union all select '#tbname3'

IF OBJECT_ID('tempdb..#tbname1') IS NOT NULL
DROP TABLE #tbname1
create table #tbname1(goodsno varchar(max))
insert into #tbname1 values('10011001100110011001')
insert into #tbname1 values('10021001100110011001')

IF OBJECT_ID('tempdb..#tbname2') IS NOT NULL
DROP TABLE #tbname2
create table #tbname2(goodsno varchar(max))
insert into #tbname2 values('66ads1001100110011001')

IF OBJECT_ID('tempdb..#tbname3') IS NOT NULL
DROP TABLE #tbname3
create table #tbname3(goodsno varchar(max))
insert into #tbname3 values('30011001100110011001')

IF OBJECT_ID('tempdb..#tablenamesAddRowNum') IS NOT NULL
DROP TABLE #tablenamesAddRowNum
select IDENTITY(int,1,1) rowindex,tbname into #tablenamesAddRowNum from #tablenames order by tbname
---------------------第一步:end----------------------


---------------------第二步:begin----------------------
select * from #tbname1
select * from #tbname2
select * from #tbname3
---------------------第二步:end----------------------

初始数据结果:


---------------------第三步:begin----------------------
declare @tbname varchar(30);--表名称
declare @goodsOLDvalue varchar(20);--要判断的goodsno指定值
declare @goodsNEWvalue varchar(20);--要修改的goodsno指定值
declare @goodsnonum int;--每个表中是否存在goodsno指定值
declare @tbnum int;--表数量
declare @tbindex int;--表索引
declare @samevaluenum int;--goodsno指定值数量

select @tbnum=COUNT(*) from #tablenamesAddRowNum
set @goodsnonum=100;
set @tbindex=1;
set @samevaluenum=0;
set @goodsOLDvalue='10021001100110011001';
set @goodsNEWvalue='333333333';

while (@tbnum>=@tbindex)
begin
select @tbname=tbname from #tablenamesAddRowNum where rowindex=@tbindex
IF OBJECT_ID('tempdb..##num') IS NOT NULL
DROP TABLE ##num
--exec ('select count(*) num into ##num from '+@tbname +' where goodsno ='+@goodsNEWvalue)
exec ('select count(*) num into ##num from '+@tbname +' where goodsno ='''+@goodsNEWvalue+'''')
select @goodsnonum=num from ##num
if(@goodsnonum=0)
begin
set @samevaluenum=@samevaluenum+1;
end
set @tbindex=@tbindex+1;
end
print @tbnum;
print @samevaluenum;
set @tbindex=1;
if(@tbnum=@samevaluenum)
begin
while (@tbnum>=@tbindex)
begin
select @tbname=tbname from #tablenamesAddRowNum where rowindex=@tbindex
--exec ('update '+@tbname +' set goodsno='+@goodsNEWvalue+' where goodsno='+@goodsOLDvalue)
exec ('update '+@tbname +' set goodsno='''+@goodsNEWvalue+''''+' where goodsno='''+@goodsOLDvalue+'''')
set @tbindex=@tbindex+1;
end
end
---------------------第三步:end----------------------


---------------------第四步:begin----------------------
select * from #tbname1
select * from #tbname2
select * from #tbname3
---------------------第四步:end----------------------

修改后的结果:

原文地址:https://www.cnblogs.com/eboss/p/3837722.html