0

I need to drop all columns in an existing table in SQL Server. It is possible to delete columns by specifying each column name. I want to delete every column without specifying column name. I am looking for something like

ALTER TABLE tblUser DROP COLUMN *;

Is there any known way to do this?

6
  • 4
    Why would you want to do that? If you just want to drop the whole table, use DROP TABLE tablename Commented Dec 27, 2019 at 5:53
  • 1
    drop that table and create new Commented Dec 27, 2019 at 5:55
  • 2
    Without columns, tables are only a name. If you are dropping all the columns, you may consider dropping the whole table with DROP TABLE tablename Commented Dec 27, 2019 at 5:58
  • Specify all the column names to remove.. this can be done programmatically with “dynamic SQL”, including generation from an external language. Deleting the table itself has slightly different connotations. Commented Dec 27, 2019 at 6:00
  • I don't think SQL Server even allows tables without columns. Commented Dec 27, 2019 at 6:12

3 Answers 3

3

Answering your question literally, no you can't. If you try to remove the last column, SQL Server will throw the following error:

Msg 4923, Level 16, State 1, Line 12

ALTER TABLE DROP COLUMN failed because 'Id' is the only data column in table 'NoColumns'. A table must have at least one data column.

As such, if you actually want to solve your problem, whatever it is, it would be best to voice the initial problem and not the solution you decided to pursue.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead remove all the columns, you could drop the table

DROP TABLE TABLENAME

Or You can mention all the column names in Alter query

ALETR TABLE TableName DROP COLUMN Column1, Column2, Column3....ColumnN

2 Comments

Hi Thank you for the comments, In my case the columns are dynamic and I have to do another insert with different number of columns right after dropping the first set of columns to the same table. I tried dropping the table and inserting it, but it throws errors related to batch, my problem here is I need to be stay in same batch also, so a GO statement also not useful. Is there any way we stay in same batch and do a drop table tblUser; INSERT INTO tblUser select * from anotherTable
@NewDeveloper Then do first add all the columns and remove all old columns using ALTER TABLE
0
SELECT COLUMN_NAME INTO #result FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME= N'tablename' AND COLUMN_NAME != 'Guid' -- or id
DECLARE @sql NVARCHAR(MAX) = '';
DECLARE @colNames NVARCHAR(MAX) = '';
SELECT @colNames += '['+ r.COLUMN_NAME + ']' +',' from #result r;
SET @colNames = LEFT(@colNames,LEN(@colNames)-1)
DROP TABLE #result;
SET @sql = 'ALTER TABLE tablename DROP COLUMN ' + @colNames;
EXEC sp_executesql @sql

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.