首页 > 解决方案 > 如何在 SQL Server 中删除多个列

问题描述

我有多个列

数据库名称:dbo.Test

列名(示例):

ABC_1 | DEF_2 | GHI_3 | JKL_4 | MNO_5 | PQR_6 | STU_7

如何编写可以删除列的查询,GHI_3直到STU_7使用循环?

标签: sqlsql-server

解决方案


您不需要编写循环来执行此操作,一种方法是使用sys.columnstable 获取要删除的所有列。

假设您要删除除 ' Col11' 和 ' Col2' 之外的所有列,在这种情况下,您可以编写如下查询。

declare @dropstmt as nvarchar(max) ='alter table Test  drop column ' 
                          +  stuff((select ', ' + quotename(name) 
             from   
             (
                select c.name 
                from sys.columns c
                    JOIN sys.tables t ON c.object_id = t.object_id
                where t.name = 'test'
                and c.name  not in('col1','col2')
             )t
             for xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''); 
print @dropstmt
exec sp_executesql @dropstmt  

推荐阅读