DROP all columns from an existing SQL Server table - sql-server

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?

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.

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

Related

SQL Server 2012: ALTER TABLE ALTER COLUMN MyColumn1 fails because one or more objects access this column

I have a table which contains MyColumn1 with user defined datatype of CustomDatatype INT NOT NULL. I need to change this column to a VARCHAR(5), but I am getting the following errors:
Msg 5074, Level 16, State 1, Line 12
The object 'CustomDatatype' is dependent on column 'MyColumn1'.
Msg 4922, Level 16, State 9, Line 12
ALTER TABLE ALTER COLUMN MyColumn1 failed because one or more objects access this column.
This does not seem to be related to an index or foreign key reference which I would omit to drop before altering the column datatype, this seems to be directly related to the originally used custom defined datatype CustomDatatype on this column.
How can I change MyColumn1's datatype without dropping the CustomDatatype because that could create apocalyptic scenario in my system or dropping the table?
Thanks
Update (2018-07-31): I found a response to the same question in different forum where it states: "...This is the problem with UDT columns. You will need to drop all the columns of this type first in all tables (and may be in functions / SPs, views), then delete the type and create correct type, then re-create all the columns..." (Naomi 2011) from Microsoft (August 2, 2011) web: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/b7bf0f04-dee8-4751-803b-4c3e1f7f7c70/how-to-change-column-nametype-of-user-defined-table-type?forum=transactsql
So far the only viable solutions I came up with are to:
Create a copy of the table (script it out with all
dependencies i.e.: triggers, indexes, keys, etc.) Drop the original
table (which is ok to do even though custom datatypes are specified) and then recreate the table again with the new datatype column.
If the table cannot be dropped (for some reason) rename the old
datatype column, create a new column with the original column name
with the right datatype. Move the data from the old (renamed) column
into the new one (make sure to mind the triggers,etc.). Then force
to recompile all the Sprocs and refresh all the views which are
dependent.
Can you check if there is any Index added for those column?
If yes,
you will need to drop and recreate the index.
once you drop the constraints and index , you can alter the column.
alter table Table1
alter column MyColumn1 varchar(5);
Then re-create constraints and index.
So far the only viable solutions I came up with are to:
1) Create a copy of the table (script it out with all dependencies i.e.: triggers, indexes, keys, etc.) Drop the original table (which is ok to do even though custom datatypes are specified) and then recreate the table again with the new datatype column.
2) If the table cannot be dropped (for some reason) rename the old datatype column, create a new column with the original column name with the right datatype. Move the data from the old (renamed) column into the new one (make sure to mind the triggers,etc.). Then force to recompile all the Sprocs and refresh all the views which are dependent.

How to add HIDDEN property on column?

When temporal table is created, we need to defined start and end date time columns
which can be hidden - not visible in SELECT * or INSERT without columns. I want to add one more column, which will contain information about the user who has commit the change.
The issue is, I am getting the following error:
Msg 13735, Level 16, State 1, Line 10
Cannot alter HIDDEN attribute on column 'UserID' in table 'GK' because this column is not a generated always column.
Here is the code:
DROP TABLE IF EXISTS GK;
CREATE TABLE GK
(
[ID] INT
,[UserID] BIGINT DEFAULT (CONVERT(BIGINT, SESSION_CONTEXT(N'user_id')))
)
ALTER TABLE GK
ALTER COLUMN [UserID] ADD HIDDEN;
Why I am not allowed to add this attribute on such column?
FOR this you need to use like below
[ GENERATED ALWAYS AS ROW { START | END } [ HIDDEN ] ]
GENERATED ALWAYS AS ROW START/END is compulsory. and
Also note that System-versioned table cannot have more than one 'GENERATED ALWAYS AS ROW END' column
Also note that System-versioned table cannot have more than one 'GENERATED ALWAYS AS ROW START' column
So if you are already using 2 dates column then it will not be possible.
I think we can just use a normal column with default value.
Refer more from Microsoft - https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql
Th correct answer here is that we can add this property only for temporal tables date columns (currently).
If the versioning is stopped and the columns are not hidden, the property is added like this:
ALTER TABLE dbo.Department
ALTER COLUMN SysStartTime ADD HIDDEN;
ALTER TABLE dbo.Department
ALTER COLUMN SysEndTime ADD HIDDEN;
There is a commercial product called DBDefence. It can mask and also completely hide columns in tables for certain logins. It is available for all SQL Servers starting from SQL Server R2.
Disclaimer: I'm associated with the vendor.

Sql query for alter Table

I'm trying to alter a table and add a column at position which is after an existing column,
but I can't make it since getting the following
error:
Msg 102, Level 15, State 1, Line 2 Incorrect syntax near 'AFTER'.
and the query I used is:
ALTER TABLE DealerGroup
ADD Status varchar(50)
AFTER Description;
Microsoft SQL Server does not support the after part, which I believe is specific to MySQL.
In any case the internal ordering of columns should not matter to you, unless you rely on getting an ordered result when doing select * which you shouldn't do anyway.
You can't add a column to a specific position in a table. Actually the RDBMS (SQL Server in this case) doesn't care where a column resides in the order of a table.
When you add another column to a table, it always goes "last".
You cannot add the column after specified column because in database structure column order doesn't matter when you need to fetch the data, and also AFTER is not any keyword defined in it in case of alter table query.
OR if you still want to, then you have to drop the table and re-create it with required column ordering.

How to remove a column from an existing table?

How to remove a column from an existing table?
I have a table MEN with Fname and Lname
I need to remove the Lname
How to do it?
ALTER TABLE MEN DROP COLUMN Lname
Generic:
ALTER TABLE table_name DROP COLUMN column_name;
In your case:
ALTER TABLE MEN DROP COLUMN Lname;
Your example is simple and doesn’t require any additional table changes but generally speaking this is not so trivial.
If this column is referenced by other tables then you need to figure out what to do with other tables/columns. One option is to remove foreign keys and keep referenced data in other tables.
Another option is to find all referencing columns and remove them as well if they are not needed any longer.
In such cases the real challenge is finding all foreign keys. You can do this by querying system tables or using third party tools such as ApexSQL Search (free) or Red Gate Dependency tracker (premium but more features). There a whole thread on foreign keys here
This is the correct answer:
ALTER TABLE MEN DROP COLUMN Lname
But... if a CONSTRAINT exists on the COLUMN, then you must DROP the CONSTRAINT first, then you will be able to DROP the COLUMN. In order to drop a CONSTRAINT, run:
ALTER TABLE MEN DROP CONSTRAINT {constraint_name_on_column_Lname}
In SQL Server 2016 you can use new DIE statements.
ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name
The above query is re-runnable it drops the column only if it exists in the table else it will not throw error.
Instead of using big IF wrappers to check the existence of column before dropping it you can just run the above DDL statement
The question is, can you only delete a column from an unexisting table ;-)
BEGIN TRANSACTION
IF exists (SELECT * FROM sys.columns c
INNER JOIN sys.objects t ON (c.[object_id] = t.[object_id])
WHERE t.[object_id] = OBJECT_ID(N'[dbo].[MyTable]')
AND c.[name] = 'ColumnName')
BEGIN TRY
ALTER TABLE [dbo].[MyTable] DROP COLUMN ColumnName
END TRY
BEGIN CATCH
print 'FAILED!'
END CATCH
ELSE
BEGIN
SELECT ERROR_NUMBER() AS ErrorNumber;
print 'NO TABLE OR COLUMN FOUND !'
END
COMMIT
The simple answer to this is to use this:
ALTER TABLE MEN DROP COLUMN Lname;
More than one column can be specified like this:
ALTER TABLE MEN DROP COLUMN Lname, secondcol, thirdcol;
From SQL Server 2016 it is also possible to only drop the column only if it exists. This stops you getting an error when the column doesn't exist which is something you probably don't care about.
ALTER TABLE MEN DROP COLUMN IF EXISTS Lname;
There are some prerequisites to dropping columns. The columns dropped can't be:
Used by an Index
Used by CHECK, FOREIGN KEY, UNIQUE, or PRIMARY KEY constraints
Associated with a DEFAULT
Bound to a rule
If any of the above are true you need to drop those associations first.
Also, it should be noted, that dropping a column does not reclaim the space from the hard disk until the table's clustered index is rebuilt. As such it is often a good idea to follow the above with a table rebuild command like this:
ALTER TABLE MEN REBUILD;
Finally as some have said this can be slow and will probably lock the table for the duration. It is possible to create a new table with the desired structure and then rename like this:
SELECT
Fname
-- Note LName the column not wanted is not selected
INTO
new_MEN
FROM
MEN;
EXEC sp_rename 'MEN', 'old_MEN';
EXEC sp_rename 'new_MEN', 'MEN';
DROP TABLE old_MEN;
But be warned there is a window for data loss of inserted rows here between the first select and the last rename command.
To add columns in existing table:
ALTER TABLE table_name
ADD
column_name DATATYPE NULL
To delete columns in existing table:
ALTER TABLE table_name
DROP COLUMN column_name
This can also be done through the SSMS GUI. The nice thing about this method is it warns you if there are any relationships on that column and can also automatically delete those as well.
Put table in Design view (right click on table) like so:
Right click on column in table's Design view and click "Delete
Column"
As I stated before, if there are any relationships that would also need to be deleted, it will ask you at this point if you would like to delete those as well. You will likely need to do so to delete the column.
If you are using C# and the Identity column is int, create a new instance of int without providing any value to it.It worked for me.
[identity_column] = new int()
Syntax:
ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
For Example:
alter table Employee drop column address;

Alter Table Drop Column Failed

I'm trying to clean up a database table and I'd really like to drop two columns as they should no longer be being used.
'Property' table
- Unable to modify table.
The index '_dta_index_Property_7_669245439__K1_K9_K8_K24_K4_2_5_6_13_22_25_26_29' is dependent on column 'AveragePriceMta'.
The index '_dta_index_Property_7_669245439__K1_K9_K8_K24_2_4_5_6_7_13_22_25_26_29' is dependent on column 'AveragePriceMta'.
ALTER TABLE DROP COLUMN AveragePriceMta failed because one or more objects access this column.
I've gone and looked at the indexes for this table found the particular columns I want to delete in a greyed out field of "Included columns". Obviously I don't want to just drop these indexes - but is there a way to refresh the index so that I can remove the columns in question out of the non-editable included columns field?
Using SQL Server 2008 but database is 2005.. in case that matters.
Thanks for your help! :)
You can't add or remove columns to an Index. You will have to drop the index and the re-create it.
You can you use Create Index along with the Drop_Existing clause to do this.
MS Help on Create Index

Resources