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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With