使用alter table中的子查询删除多个列

时间:2015-12-08 07:07:53

标签: sql-server tsql subquery alter-table

我需要从表格中删除所有列,但我不提前知道这些列的数量和名称。我想从sys.columns中获取列名,然后删除除少数之外的所有列。我需要这样的东西:

alter table Table
drop column (
            select a.name as ColumnName 
            from sys.all_columns a
            INNER JOIN sys.tables b
            on a.object_id = b.object_id
            where b.name = 'Table'
            where a.name NOT IN (
                                     RowID, 
                                     RemoteUserId, 
                                     Email, 
                                     FirstName, 
                                 )
            )

1 个答案:

答案 0 :(得分:0)

首先您需要创建Function以将Comma Separated Strings拆分为Rows

CREATE FUNCTION [dbo].[FnSplit]
(
@List nvarchar(2000),
@SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(

Id int identity(1,1),
Value nvarchar(100)
) 
AS  
BEGIN
While (Charindex(@SplitOn,@List)>0)
Begin 
Insert Into @RtnValue (value)
Select
Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1))) 
Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
End 

Insert Into @RtnValue (Value)
Select Value = ltrim(rtrim(@List))
Return
END
GO

然后在Stored Procedure下面创建

 Create Procedure DropColumnExceptGivn
 @table  varchar(50),
 @Column Varchar(max)
 AS
 BEGIN
 SET NOCOUNT ON;
      declare @variables AS TABLE (cols varchar(max))
      declare @sql varchar(max) = ''
      declare @sql1 varchar(max) = ''
      declare @cols nvarchar(max) =''


  set @sql1 = 'SELECT Stuff((select '',''+ Column_name '+'from INFORMATION_SCHEMA.COLUMNS where 
            table_name = ' +''''+@table+''''+
            ' and column_name not in (SELECT Value FROM dbo.FnSplit('+''''+@column+''''+','','')) 
            for xml path('''')),1,1,'''')'
  print @sql1

  insert into @variables
  exec (@sql1)  
  select @cols = cols  from @variables 
  select @cols 

  set @sql= 'alter table '+ @table + ' drop column ' + @cols 

  print @sql 

  exec (@sql)
  end

  go

- 创建样本表

Create table pets1 (petid int, PetTypeID int, PetName Varchar(20),OwnerId int)
go

然后执行以下Stored Procedure.                                                                                              参数为:1。表名2.列必须为左(逗号分隔值)

exec DropColumnExceptGivn 'pets1','PetID, PetTypeID'

go
select *from pets1

希望这会有所帮助