一个表有N多列,如何指定删除表的的一定数量的列及相应数据,求语句

解决方案 »

  1.   

    --注意:@n必须小于表中数据总列数,可以自己增加判断,如果n>count(*) 直接DROP Table [tableName]create procedure p_clearColumn (
      @n int,     --列数 
      @tableName nvarchar (50) --表名
    )
    as 
     
    declare @sql nvarchar(500)set @sql='select top '+str(@n)+' [name] into tmpCol  from syscolumns  where id = (select TOP 1 ID from sysobjects where [name]='''+@tableName+''') order by colorder ASC'
    exec(@sql)declare @sql2 nvarchar(200)
    set @sql2 ='alter table '+@tableName+' drop column '
    declare  @col nvarchar(4000)
    set @col ='' 
    select @col=@col+ name+',' from tmpColif len(@col) <2
    begin
        return
    end 
    else
    begin
        set @col =substring(@col,0,len(@col)) 
    endset @sql2 =@sql2 +@col
       
    drop table tmpCol
    exec (@sql2)