How to remove a column from an existing table? - sql-server

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;

Related

DROP all columns from an existing SQL Server table

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

How does SQL Server Database Project: Publish decide when to recreate a table?

I have a SQL Server Database Project in which I've made several changes to the schema where I've changed column data types from NUMERIC (18,0) to INT. We're trying to normalize the data type used for Primary Keys, it's a currently 50/50 mix.
When I generate the Publish script, some of the tables are recreated in the script:
CREATE TABLE [dbo].[tmp_XYZ]
INSERT TABLE [dbo].[tmp_XYZ] SELECT ... FROM [dbo].[XYZ]
DROP TABLE [dbo].[XYZ]
sp_rename N'[dbo].[tmp_XYZ]', N'XYZ';
but other tables are just updated via ALTER statements
ALTER TABLE [dbo].[ABC] ALTER COLUMN [AbcID] INT NULL;
Is there some rule that dictates when a table will be recreated, and when it's just altered in place ?
Probably the best way is to Right Click on your object name and choose script as ...
Then you have options to create or alter
If you couldn't find Alter ,you can go to design view, right click and choose Generate Change Script ... to find the alter statement.
This is just an easy problem. It's the same problem as changing a table in the table designer. I think you've changed a column inside your table design which needs to drop and recreate the table to let the column order in the same position.
Here is a short example. Take this table design as given:
CREATE TABLE dbo.Test(
id int identity(1,1),
firstname nvarchar(100),
name nvarchar(100),
street nvarchar(100)
)
This will create the columns in a specified order. You can see this order here:
SELECT name, column_id
FROM sys.columns
WHERE object_id = OBJECT_ID(N'dbo.Test')
You'll see something like that:
column_name column_id
id 1
firstname 2
name 3
street 4
If you change the the column name via designer or in your case in the data project, this will cause SQL Server to obtain this order upright.
In this case you try to change the column name to lastname. This will enforce SQL Management Studio and other programs like that to keep the column_id upright. This can only be done, if the table is completely recreated with the right columnorder. SQL Server create a temporary table stub, insert everything into it, drop the old table and rename the temporary table to the old original name. Just as in your code above.
After that you'll see something like that:
column_name column_id
id 1
firstname 2
lastname 3
street 4
If you would simply rename the last column or do it manually, everything would be fine. Manually would be much more efficient, as there isn't the need to move ALL data to a new table. The manual way would be this:
-- Create the new column
ALTER TABLE dbo.Test ADD lastname nvarchar(100)
GO
-- Populate the new column using the old one
UPDATE dbo.Test
SET lastname = name
GO
-- Drop the old column afterwards
ALTER TABLE dbo.Test DROP COLUMN name
This behavior will result in the following result:
column_name column_id
id 1
firstname 2
street 4
lastname 5
The last one will be much more efficient, as already stated.
Hopefully this will answer your question, even if the answer comes lately.

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint

I get the following message even when the table that references it is empty: "Cannot truncate table 'dbo.Link' because it is being referenced by a FOREIGN KEY constraint" Doesn't seem to make much sense why this is occurring. Any suggestions?
In SQL Server a table referenced by a FK cannot currently be truncated even if all referencing tables are empty or the foreign keys are disabled.
You need to use DELETE (may require much more logging) or drop the relationship(s) prior to using TRUNCATE and recreate them afterwards or see the workarounds on this connect item for a way of achieving this using ALTER TABLE ... SWITCH
You cannot truncate a table which has an FK constraint on it. As workaround, you could:
1/ Drop the constraints
2/ Trunc the table
3/ Recreate the constraints.
Here it is the associated T-SQL script, supposing you have 2 tables called MyTable and MyReferencedTable:
-- Remove constraint
IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_MyReferencedTable_MyTable')
BEGIN
ALTER TABLE dbo.MyReferencedTable
DROP CONSTRAINT FK_MyReferencedTable_MyTable
END
-- Truncate table
TRUNCATE TABLE dbo.MyTable
-- Re-Add constraint
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_MyReferencedTable_MyTable')
BEGIN
ALTER TABLE dbo.MyReferencedTable
WITH CHECK ADD CONSTRAINT [FK_MyReferencedTable_MyTable] FOREIGN KEY(ListingKey)
REFERENCES dbo.MyTable (ListingKey)
END
Execute the following query to search any constraint:
use MyDatabase
select c.name as c_name, t.name as t_name
from sys.key_constraints c
join sys.tables t on t.object_id = c.parent_object_id
If any constraint found on your table, remove it.
If you are receiving this error and you need to truncate the table then alternative solution could be that you can drop and re-create the table along with primary/other_keys/indexes/triggers. Please make sure that you don't need to the data in that table.
This soulution is working like a charm for me and hardly took a minute to finish. I am doing it for masking purpose.
Not for SQL Server but MySQL only.
Instead of deleting or recreating the constraint, I prefer this simpler way.
Disable the constraint validation by executing the following query first :
SET FOREIGN_KEY_CHECKS=0;
Then truncate your tables
And finally, reactivate the constraint validation :
SET FOREIGN_KEY_CHECKS=1;
Thats a common solution when you migrate databases, so you don't have to worry about the order the tables are inserted in.

How to change the data type of a column without dropping the column with query?

I have a column which has a datatype : datetime. But now i want to convert it to datatype varchar. Can i alter the datatype without droppping the column? If yes, then please explain how?
MSDN says
ALTER TABLE mytable ALTER COLUMN mycolumn newtype
Beware of the limitations of the ALTER COLUMN clause listed in the article
If ALTER COLUMN doesn't work.
It is not unusual for alter column to fail because it cannot make the transformation you desire. In this case, the solution is to create a dummy table TableName_tmp, copy the data over with your specialized transformation in the bulk Insert command, drop the original table, and rename the tmp table to the original table's name. You'll have to drop and recreate the Foreign key constraints and, for performance, you'll probably want to create keys after filling the tmp table.
Sound like a lot of work? Actually, it isn't.
If you are using SQL Server, you can make the SQL Server Management Studio do the work for you!
Bring up your table structure (right-click on the table column and select "Modify")
Make all of your changes (if the column transformation is illegal, just add your new column - you'll patch it up in a moment).
Right-click on the background of the Modify window and select "Generate Change Script." In the window that appears, you can copy the change script to the clipboard.
Cancel the Modify (you'll want to test your script, after all) and then paste the script into a new query window.
Modify as necessary (e.g. add your transformation while removing the field from the tmp table declaration) and you now have the script necessary to make your transformation.
ALTER TABLE [table name] MODIFY COLUMN [column name] datatype
ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)
Type the below query:
alter table table_Name alter column column_name datatype
e.g.
alter table Message alter column message nvarchar(1024);
ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)
With SQL server 2008 and more, using this query:
ALTER TABLE [RecipeInventorys] ALTER COLUMN [RecipeName] varchar(550)
This work for postgresql 9.0.3
alter table [table name] ALTER COLUMN [column name] TYPE [character varying];
http://www.postgresql.org/docs/8.0/static/sql-altertable.html
ALTER TABLE [table_name] ALTER COLUMN [column_name] varchar(150)
ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20) this is perfect for change to datatype
ORACLE - Alter table table_name modify(column_name new_DataType);
ALTER TABLE yourtable MODIFY COLUMN yourcolumn datatype
ALTER TABLE table_name
MODIFY (column_name data_type);
ALTER tablename MODIFY columnName newColumnType
I'm not sure how it will handle the change from datetime to varchar though, so you may need to rename the column, add a new one with the old name and the correct data type (varchar) and then write an update query to populate the new column from the old.
http://www.1keydata.com/sql/sql-alter-table.html
alter table [table name] remove [present column name] to [new column name.

How do I add the identity property to an existing column in SQL Server

In SQL Server (in my case, 2005) how can I add the identity property to an existing table column using T-SQL?
Something like:
alter table tblFoo
alter column bar identity(1,1)
I don't beleive you can do that. Your best bet is to create a new identity column and copy the data over using an identity insert command (if you indeed want to keep the old values).
Here is a decent article describing the process in detail:
http://www.mssqltips.com/tip.asp?tip=1397
The solution posted by Vikash doesn't work; it produces an "Incorrect syntax" error in SQL Management Studio (2005, as the OP specified). The fact that the "Compact Edition" of SQL Server supports this kind of operation is just a shortcut, because the real process is more like what Robert & JohnFX said--creating a duplicate table, populating the data, renaming the original & new tables appropriately.
If you want to keep the values that already exist in the field that needs to be an identity, you could do something like this:
CREATE TABLE tname2 (etc.)
INSERT INTO tname2 FROM tname1
DROP TABLE tname1
CREATE TABLE tname1 (with IDENTITY specified)
SET IDENTITY_INSERT tname1 ON
INSERT INTO tname1 FROM tname2
SET IDENTITY_INSERT tname1 OFF
DROP tname2
Of course, dropping and re-creating a table (tname1) that is used by live code is NOT recommended! :)
Is the table populated? If not drop and recreate the table.
If it is populated what values already exist in the column? If they are values you don't want to keep.
Create a new table as you desire it, load the records from your old table into your new talbe and let the database populate the identity column as normal. Rename your original table and rename the new one to the correct name :).
Finally if the column you wish to make identity currently contains primary key values and is being referenced already by other tables you will need to totally re think if you're sure this is what you want to do :)
There is no direct way of doing this except:
A) through SQL i.e.:
-- make sure you have the correct CREATE TABLE script ready with IDENTITY
SELECT * INTO abcTable_copy FROM abcTable
DROP TABLE abcTable
CREATE TABLE abcTable -- this time with the IDENTITY column
SET IDENTITY_INSERT abcTable ON
INSERT INTO abcTable (..specify all columns!) FROM (..specify all columns!) abcTable_copy
SET INDENTITY_INSERT abcTable OFF
DROP TABLE abcTable_copy
-- I would suggest to verify the contents of both tables
-- before dropping the copy table
B) Through MSSMS which will do exactly the same in the background but will less fat-fingering.
In the MSSMS Object Explorer right click the table you need to modify
Select "design" Select the column you'd like to add IDENTITY to
Change the identity setting from NO -> YES (possibly seed)
Ctr+S the table
This will drop and recreate the table with all original data in it.
If you get a warning:
Go to MSSMS Tools -> Options -> Designers -> Table and database Designers
and uncheck the option "Prevent saving changes that require table re-creation"
Things to be careful about:
your DB has enough disk space before you do this
the DB is not in use (especially the table you are changing)
make sure to backup your DB before doing it
if the table has a lot of data (over 1G) try it somewhere else first
before using in real DB
Create a New Table
SELECT * INTO Table_New FROM Table_Current WHERE 1 = 0;
Drop Column from New Table
Alter table Table_New drop column id;
Add column with identity
Alter table Table_New add id int primary key identity;
Get All Data in New Table
SET IDENTITY_INSERT Table_New ON;
INSERT INTO Table_New (id, Name,CreatedDate,Modified)
SELECT id, Name,CreatedDate,Modified FROM Table_Current;
SET IDENTITY_INSERT Table_New OFF;
Drop old Table
drop table Table_Current;
Rename New Table as old One
EXEC sp_rename 'Table_New', 'Table_Current';
alter table tablename
alter column columnname
add Identity(100,1)

Resources