IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_sys_gen_updatestatement]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_sys_gen_updatestatement]
GO
CREATE PROCEDURE [dbo].[mps_sys_gen_updatestatement]
@tablename varchar(100),
@old varchar(100),
@new varchar(100),
@excludefield varchar(max),
@sql varchar(max) out 
AS
BEGIN
SET NOCOUNT ON;
--获取字段名称
declare @sql_paramnames varchar(max)
declare @sql_paramtypes varchar(max)
declare @s varchar(max)
declare @fieldname varchar(max)
declare @ss varchar(max)
declare @fieldtype varchar(max)
declare @index int
declare @index2 int
declare @nonedate datetime 
set @nonedate = CONVERT(datetime,'1910-1-1')
if (@old>'') set @old=@old+'.'
if (@new>'') 
begin
if (@new='@')  set @new=@new else set @new=@new+'.'
end 

exec mps_gen_proc_params_separate @tablename,@excludefield,@sql_paramnames out,@sql_paramtypes out
--处理字符串中的{}
set @sql_paramnames=REPLACE(@sql_paramnames,'{','')
set @sql_paramnames=REPLACE(@sql_paramnames,'}','')
--分离并组装字符串
set @sql=''
set @s=@sql_paramnames
set @ss=@sql_paramtypes
while (@s>'') 
begin
set @index=CHARINDEX(',',@s)
set @index2=CHARINDEX('|',@ss)
if (@index>0)
begin
set @fieldname = substring(@s,1,@index-1) 
set @s  = substring(@s,@index+1,len(@s)-@index)

set @fieldtype = substring(@ss,1,@index2-1) 
set @ss  = substring(@ss,@index2+1,len(@ss)-@index2)
end else 
begin
set @fieldname = @s 
set @fieldtype = @ss  
set @s = '' 
set @ss = '' 
end 
if (@fieldname>'')
begin
set @sql+=''+@fieldname + '='
set @sql+= 
case when CHARINDEX('char',@fieldtype) >0 
 or CHARINDEX('text',@fieldtype) >0 
 then 'case when '+@new+@fieldname+' is null or '+@new+@fieldname+' = ''_none_'' '+
 ' then '+@old+@fieldname+' else '+@new+@fieldname+' end,'+CHAR(13) 
else case when CHARINDEX('int',@fieldtype) > 0 
 or CHARINDEX('decimal',@fieldtype) > 0 
 or CHARINDEX('numeric',@fieldtype) > 0 
 or CHARINDEX('real',@fieldtype) > 0
 or CHARINDEX('float',@fieldtype) > 0 
then 'case when ' + @new+@fieldname+' is null or '+@new+@fieldname+' = -999999999 '+
 ' then '+@old+@fieldname+' else '+@new+@fieldname+' end,'+CHAR(13)
else case when CHARINDEX('datetime',@fieldtype) > 0
then 'case when ' + @new+@fieldname+' is null or '+@new+@fieldname+' = @nonedate '+
 'then '+@old+@fieldname+' else '+@new+@fieldname+' end,'+CHAR(13)
end end end
end
end
--去掉末尾多余的逗号
if CHARINDEX(',',@sql) > 0
set @sql=SUBSTRING(@sql,1,LEN(@sql)-2)
--select @sql
END