日期:2014-05-18  浏览次数:20358 次

sql连接查询语句的编写
一个库里有30张表,名称分别是r1,r2...到r30。表的结构都一致,只有数据有差异。如何写一条语句将这30张表的内容都查询出来?
我看用union写出来的有点长,问问看还有啥方法

------解决方案--------------------
SQL code

declare @sql varchar(max)
declare @i int
set @i = 1
while @i <= 30
begin
select @sql = isnull(@sql+' union all ','') + ' select * from r'+ltrim(@i)
set @i = @i + 1
end

print @sql
exec(@sql)