IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_compare_table]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_compare_table]
GO
-- =============================================
-- Author:  flobit
-- Create date: May 16 2018 10:34AM
-- Description: 根据mps_field_info
-- 1.先根据fldi_update获取哪些表需要比对
-- 2.逐个判断表是否存在,调用不同的存储过程生成需要执行的SQL
-- 3.如果生成的SQL不为空,则插入SQL表中
-- 4.返回需要执行的SQL
-- =============================================
CREATE PROCEDURE [dbo].[mps_compare_table]
@cmpid int
AS
BEGIN
SET NOCOUNT ON;
DECLARE @tablename_with_database table(name varchar(256) primary key)
DECLARE @tb_operation_sql table(tb_name varchar(256),tb_operation varchar(32),tb_opsql varchar(max))
insert into @tablename_with_database
select distinct case when fldi_database IS NULL or fldi_database='' then DB_NAME()+'.dbo.' else fldi_tbname end +fldi_tbname 
from mps_fieldinfo 
where fldi_changed=0 and fldi_cmpid=@cmpid
--处理修改表
--select * from @tablename_with_database
declare @tablename varchar(512)=''
declare @sql varchar(max)=''
declare @type varchar(32)=''
declare table_names  cursor LOCAL for select * from @tablename_with_database
open table_names
while 1=1
begin
fetch next from table_names into @tablename
if @@FETCH_STATUS!=0
break;
set @sql=''
if OBJECT_ID(@tablename) IS NULL --如果这个表不存在
begin
set @type='CREATE_TABLE'
execute mps_gen_create_table @cmpid,@tablename,@sql out
end else                         --表存在
begin
set @type='ALTER_TABLE'
execute mps_gen_alter_table @cmpid,@tablename,@sql out
end
if @sql!='' --如果存储过程返回了数据
begin
insert into @tb_operation_sql values(@tablename,@type,@sql);
end
end
close table_names

select tb_opsql,tb_name,tb_operation from @tb_operation_sql
END