IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[gen_sql_insert]') AND type = 'P')
DROP PROCEDURE [dbo].[gen_sql_insert]
GO
CREATE PROCEDURE [dbo].[gen_sql_insert]
@condition varchar(max),
@source varchar(max),
@target varchar(max)='',
@excludeFiled varchar(max)='',
@deleteIdentity varchar(max)=''
AS
BEGIN
SET NOCOUNT ON;
declare @sql_insert_base varchar(max)
declare @sql_delete_base varchar(max)
declare @columns varchar(max)
declare @sql nvarchar(max)
set @sql=''
set @target = case when LEN(@target) >0 then @target else @source end
set @condition = case when LEN(@condition)>0 then ' and '+@condition else @condition end;
exec get_columns @source,@excludeFiled,@columns out
--生成基本的INSERT SQL
set @sql_delete_base = 'delete from '+@target+' where '+@deleteIdentity+' = '
set  @sql_insert_base= 'insert into '+@target+'('+@columns+') values('''
--在基本SQL的基础上装填数据
if LEN(@deleteIdentity)>0
begin
set @sql = 'select @sql_delete_base +''''''''+'+@deleteIdentity+'+''''''''+'';''+char(13)+char(10)+@sql_insert_base + REPLACE('+REPLACE(@columns,',',' ,'''''''','''''''''''')+''''''''+'',''+''''''''+REPLACE(')+' ,'''''''','''''''''''')+'''''');'' as insert_sql_text from '+@source +' where 1=1 '+@condition;
exec sp_executesql @sql,N'@sql_delete_base varchar(max),@sql_insert_base varchar(max)',@sql_delete_base,@sql_insert_base
end else
begin
set @sql = 'select @sql_insert_base + REPLACE('+REPLACE(@columns,',',' ,'''''''','''''''''''')+''''''''+'',''+''''''''+REPLACE(')+' ,'''''''','''''''''''')+'''''');'' as insert_sql_text from '+@source +' where 1=1 '+@condition;
exec sp_executesql @sql,N'@sql_insert_base varchar(max)',@sql_insert_base
end
END
/*
exec master.dbo.[gen_sql_insert] 'sql_name like ''%report%''','ebs_kernel.dbo.pub_sql','','','sql_name'
*/