IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_get_querycode_by_biz]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_get_querycode_by_biz]
GO
CREATE procedure [dbo].[mps_get_querycode_by_biz]
@bizid bigint,
@biz2tag bigint = 0,
@containSysField int = 0 ,
@forinsert bigint = 0
as
begin

select a+' '+b+' '+c querycode
from (
select top 1 0 o,case when @forinsert = 0 then 'select ' else 'insert into '+fldi_tbname+'(' end a, ' ' b ,'' c
from ebs2java.dbo.mps_fieldinfo
where fldi_tbid = @bizid
and fldi_ord2tag = 0 and LEN(fldi_fieldname)>4
union
select ROW_NUMBER() over(order by fldi_id) o,
case when ROW_NUMBER() over(order by fldi_id) = 1 then fldi_fieldname else ','+fldi_fieldname end a,
case when @forinsert = 0 then '['+fldi_fieldcaption+']' else '--['+fldi_fieldcaption+']' end b,
'--'+fldi_datatype c
from ebs2java.dbo.mps_fieldinfo
where fldi_tbid = @bizid and case when @containSysField>1 then -1 else fldi_system end = case when @containSysField>1 then -1 else @containSysField end
and fldi_ord2tag = 0 and LEN(fldi_fieldname)>4
union
select TOP 1 99999999 as o ,
case when @forinsert = 0 then 'from ' else ')' end a,
case when @forinsert = 0 then fldi_tbname+' ' else '' end b ,
'' c
from ebs2java.dbo.mps_fieldinfo
where fldi_tbid = @bizid and case when @containSysField>1 then -1 else fldi_system end = case when @containSysField>1 then -1 else @containSysField end
and fldi_ord2tag = 0 and LEN(fldi_fieldname)>4
) tb



select a+' '+b+' '+c querycode
from (
select top 1 0 o,case when @forinsert = 0 then 'select ' else 'insert into '+fldi_tbname+'(' end a, ' ' b ,'' c
from ebs2java.dbo.mps_fieldinfo
where fldi_tbid = @bizid
and fldi_ord2tag = @biz2tag and LEN(fldi_fieldname)>4
union
select ROW_NUMBER() over(order by fldi_id) o,
case when ROW_NUMBER() over(order by fldi_id) = 1 then fldi_fieldname else ','+fldi_fieldname end a,
case when @forinsert = 0 then '['+fldi_fieldcaption+']' else '--['+fldi_fieldcaption+']' end b,
'--'+fldi_datatype c
from ebs2java.dbo.mps_fieldinfo
where fldi_tbid = @bizid and case when @containSysField>1 then -1 else fldi_system end = case when @containSysField>1 then -1 else @containSysField end
and fldi_ord2tag = @biz2tag and LEN(fldi_fieldname)>4
union
select TOP 1 99999999 as o ,
case when @forinsert = 0 then 'from ' else ')' end a,
case when @forinsert = 0 then fldi_tbname+' ' else '' end b ,
'' c
from ebs2java.dbo.mps_fieldinfo
where fldi_tbid = @bizid and case when @containSysField>1 then -1 else fldi_system end = case when @containSysField>1 then -1 else @containSysField end
and fldi_ord2tag = @biz2tag and LEN(fldi_fieldname)>4
) tb

end