IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_ord_jobs_available]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_ord_jobs_available]
GO
CREATE procedure [dbo].[mps_g_ord_jobs_available](
@cmpid int ,
@bizid int ,
@ordid bigint 
) as
begin
set nocount on
declare @sql nvarchar(2000) 
declare @db varchar(100) 
declare @tbid int 
declare @finished int 
select @db=biz_database , @tbid=biz_table from mps_biztype where biz_id=@bizid 
if (@db>'') set @db=@db+'.dbo.' 
if (@tbid=0) set @db=@db+'order_'+ltrim(rtrim(str(@bizid))) else set @db=@db+'order_'+ltrim(rtrim(str(@tbid)))

set @sql = ' select @finished=ord_finished from '+@db+' where ord_id=@ordid ' 
exec sp_executesql @sql, N'@finished int out,@ordid bigint', @finished out ,@ordid 
set @finished = isnull(@finished,1) 
if (@finished<10)
begin
select * from mps_job where jb_cmpid=@cmpid and jb_crmid=@bizid and jb_ordid=@ordid and jb_back=1  and jb_enabled=0 order by jb_id 
end else 
begin
  select * from mps_job_history where jb_cmpid=@cmpid and jb_crmid=@bizid and jb_ordid=@ordid and jb_back=1     order by jb_id 
end
set nocount off
end