Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop multiple columns in SQL Server

Tags:

sql

sql-server

I have multiple columns

Dbname: dbo.Test

Column's name (example) :

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

How can I write queries that can drop column GHI_3 until STU_7 using a loop?

like image 724
ken Avatar asked Feb 28 '19 03:02

ken


People also ask

How do I drop multiple columns in SQL?

Multiple columns can be dropped with a single query by simply comma separating a list of DROP COLUMN statments. To drop both the "foo" and "bar" columns from the "test" table do this: ALTER TABLE test DROP COLUMN foo, DROP COLUMN bar; As many additional columns can be added to the list as required.

How do I drop all columns in a table in SQL?

Delete columns using Object Explorer In Object Explorer, connect to an instance of Database Engine. In Object Explorer, locate the table from which you want to delete columns, and expand to expose the column names. Right-click the column that you want to delete, and choose Delete. In Delete Object dialog box, click OK.

How do I select multiple columns in SQL Server?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Is it possible to drop more than one column of a table at a time?

Multiple columns can be deleted from the MySQL table using a single ALTER statement by separating the DROP keyword and column name list with a comma.


1 Answers

You don't need to write a loop to do this, one way is using sys.columns table to get all the columns which you want to drop.

Let say you want to drop all columns except 'Col11' and 'Col2' in that case you can write your query like following.

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  
like image 125
PSK Avatar answered Sep 27 '22 21:09

PSK