IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_normalize_targetfieldinfo]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_normalize_targetfieldinfo]
GO
-- =============================================
-- Author:  flobit
-- Create date: May 17 2018 11:39AM
-- Description: 规范化临时表中从mps_fielinfo中导入的数据,
--固定处理零时表,零时表名称固定为#target_fieldinfo
-- =============================================
CREATE PROCEDURE [dbo].[mps_normalize_targetfieldinfo]
@cmpid int,
@db_name VARCHAR(128),
@tb_name VARCHAR(128)
AS
BEGIN
SET NOCOUNT ON;

IF OBJECT_ID('tempdb.dbo.#target_fieldinfo') IS NULL
BEGIN
print 'Can not found object #target_fieldinfo'
return
END
--先获取字段名称,避免错误数据导致的字段名称的重复
INSERT INTO  #target_fieldinfo ([fldi_tbname],[fldi_fieldname],[fldi_fieldcaption],[fldi_datatype],[fldi_ident],[fldi_size],[fldi_decimal],[fldi_default],[fldi_key],[fldi_index],[fldi_oldname])
SELECT DISTINCT     [fldi_tbname],[fldi_fieldname],[fldi_fieldcaption],[fldi_datatype],[fldi_ident],[fldi_size],[fldi_decimal],[fldi_default],[fldi_key],[fldi_index],[fldi_oldname]
FROM mps_fieldinfo 
where fldi_cmpid=@cmpid and (fldi_database=@db_name or (fldi_database='' and @db_name=DB_NAME()+'.dbo.')) and fldi_tbname=@tb_name

--处理数据类型
update #target_fieldinfo set fldi_datatype='int' where fldi_datatype in ('integer','number')
update #target_fieldinfo set fldi_datatype='varchar' where fldi_datatype in ('string')
--规范化默认值
--处理数值类型的缺省值
update #target_fieldinfo set fldi_default= 
case when fldi_default !='' and fldi_default is not null then fldi_default else '0' end
where fldi_datatype in ('int','bigint','decimal','numeric','float','double')
--处理日期类型的缺省值
update #target_fieldinfo set fldi_default=
case when fldi_default !='' and fldi_default is not null then 
case when CHARINDEX('getdate()',fldi_default) >0 or CHARINDEX('now',fldi_default) >0 then 'GETDATE()' else ''''+fldi_default+'''' end else 
'''1970-1-1''' end 
where fldi_datatype in ('date','datetime')
--处理字符串类型的缺省值
update #target_fieldinfo set fldi_default=
case when fldi_default !='' and fldi_default is not null then ''''+fldi_default+'''' else '''''' end
where fldi_datatype in ('char','nchar','varchar','nvarchar','text')
--处理max
update #target_fieldinfo set fldi_size='max'
where (fldi_datatype='nvarchar' and fldi_size>4000) OR (fldi_datatype='varchar' and fldi_size>8000)
--格式化数据类型
update #target_fieldinfo set fldi_nlzdatatype=fldi_datatype
update #target_fieldinfo set fldi_nlzdatatype='bigint'
where fldi_datatype in ('int','integer') and fldi_size > 4
update #target_fieldinfo set fldi_nlzdatatype=fldi_datatype+'('+CONVERT(VARCHAR,fldi_size)+')' where fldi_datatype in ('char','nchar','varchar','nvarchar')
update #target_fieldinfo set fldi_nlzdatatype=fldi_datatype+'('+CONVERT(VARCHAR,fldi_size)+','+CONVERT(VARCHAR,fldi_decimal)+')' where fldi_datatype in ('decimal','numeric')

END