IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[gen_params]') AND type = 'P')
DROP PROCEDURE [dbo].[gen_params]
GO

CREATE PROCEDURE [dbo].[gen_params]
@tablename varchar(100),
@excludefileds varchar(max)
AS
BEGIN
SET NOCOUNT ON;
declare @sql nvarchar(max)
declare @tbname nvarchar(100)
declare @dbname nvarchar(100)
declare @index int
declare @s varchar(max)
declare @s1 varchar(max)
declare @result nvarchar(max)
declare @parsedfields varchar(max)

--分离数据库名称和表名称
set @index=CHARINDEX('.',@tablename)
set @dbname=SUBSTRING(@tablename,1,@index-1);
set @tablename=SUBSTRING(@tablename,@index+1,LEN(@tablename)-@index);
set @index=CHARINDEX('.',@tablename)
set @tbname=SUBSTRING(@tablename,@index+1,LEN(@tablename)-@index);
select @dbname,@tbname

--分离不包含的字段名称
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
set @parsedfields=SUBSTRING(@parsedfields,1,LEN(@parsedfields)-1)+')';
select @parsedfields

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

SELECT  @result+=''@''+vcolumns.name+'' ''
+ case when vtypes.name =''sysname'' then ''navarchar'' else vtypes.name end

+ case when vtypes.name = ''sysname'' 
  or vtypes.name = ''char'' 
  or vtypes.name = ''varchar'' 
  or vtypes.name = ''nvarchar'' then  ''(''+CONVERT(varchar,vcolumns.length)+'')'' 
--decimal 怎么办
else case when vtypes.name = ''decimal'' then ''(''+CONVERT(varchar,vcolumns.xprec)+'',''+CONVERT(varchar,vcolumns.scale)+'')'' 
else '''' end end +'',''

FROM '+@dbname+'.sys.syscolumns vcolumns,'+@dbname+'.sys.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+'
set @result=substring(@result,1,len(@result)-1);'

exec sp_executesql @sql, N'@result nvarchar(4000) out,@tbname nvarchar(100)', 
@result out,@tbname
set @excludefileds=@result

END