帮帮忙 在线求解 真的急

img

还是一样的基于MS SQL Server,部分未提供表明和字段名的,我用中文代替了,实际环境需要进行替换。

create procedure 存储过程名称
as
begin TRY
    set @tagint=1 
     while @tagint<=10
        BEGIN
            set @sqlstr='select * into test'+@tagint+' from emp where 部门ID in(10,20)'  --循环拼接sql语句
            EXEC(@sqlstr) --执行sql语句
            set @tagint=@tagint+1  
        end
    --结果查询
    set @res_tagint=1
    set @res_sqlstr=''
    while @res_tagint<=10
        BEGIN
           set @res_sqlstr=@res_sqlstr+' select * from  test'+@res_tagint --循环拼接sql语句
           if @res_tagint<10
            BEGIN
                set @res_sqlstr=@res_sqlstr+' union all ' --多表合并查询拼接
            end
        end
    set @res_sqlstr='select * from ('+@res_sqlstr+') as t where empno=7788'
    EXEC(@res_sqlstr)--输出结果

end TRY
begin CATCH
print '捕获异常,输出错误'
end CATCH