IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_gen_insert_code]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_gen_insert_code]
GO
 
CREATE PROCEDURE [dbo].[mps_gen_insert_code]
@tablename varchar(100),
@prev varchar(20),
@excludefileds varchar(max),
@result varchar(max) out
AS
BEGIN
SET NOCOUNT ON;
if (@prev!='') set @prev = @prev+'.'
declare @sql nvarchar(max)
declare @tbname nvarchar(100)
declare @dbname nvarchar(100)
declare @index int
declare @s varchar(max)
declare @s1 varchar(max)
declare @parsedfields varchar(max)

--分离数据库名称和表名称
set @index=CHARINDEX('.',@tablename)
if @index > 0
begin
set @dbname=SUBSTRING(@tablename,1,@index-1)+'.sys.';
set @tablename=SUBSTRING(@tablename,@index+1,LEN(@tablename)-@index);
set @index=CHARINDEX('.',@tablename)
set @tbname=SUBSTRING(@tablename,@index+1,LEN(@tablename)-@index);
end else begin
set @dbname='sys.'
set @tbname=@tablename
end

--分离不包含的字段名称
set @parsedfields='('
set @s=@excludefileds
while (@s>'') 
begin
set @index=CHARINDEX(',',@s)
if (@index>0)
begin
set @s1 = substring(@s,1,@index-1) 
set @s  = substring(@s,@index+1,len(@s)-@index)
end else 
begin
set @s1 = @s  
set @s = '' 
end 
if (@s1>'')
begin
set @parsedfields += ''''+@s1+''''+','
end
end
if(LEN(@parsedfields) >1)
set @parsedfields=SUBSTRING(@parsedfields,1,LEN(@parsedfields)-1)+')';
else begin
set @parsedfields+=''''''+')'
end

--组装SQL语句
set @result=''
set @sql='

SELECT  @result+='''+@prev+'''+vcolumns.name+''''
+'',''
FROM '+@dbname+'syscolumns vcolumns,'+@dbname+'tables vtables,sys.types vtypes
where vtables.name=@tbname 
and vcolumns.id=vtables.object_id 
and vcolumns.xtype=vtypes.system_type_id
and vcolumns.name not in '+@parsedfields+'
and vtypes.name != ''sysname''
if LEN(@result)>0
set @result=substring(@result,1,len(@result)-1);'

--print @sql
exec sp_executesql @sql, N'@result varchar(max) out,@tbname nvarchar(100)', 
@result out,@tbname 
END