How to change a normal column to "computed" column - sql-server

I have a table in MSSQL server 2008. I would like to change one of the column in that table to computed column. Could somebody tell me how do I do that ?

Preserve the old data:
EXEC sp_rename 'MyTable.OldCol', 'RenamedOldCol', 'COLUMN';
Add computed column
ALTER TABLE MyTable ADD ComputedCol AS (some expression);
Then, when you're happy
ALTER TABLE MyTable DROP COLUMN RenamedOldCol;

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 to alter the column name in a table from front end?

In my database I have a table with columns col1,col2,col3.
I want to give the fourth column i.e..,col4 from the front end(when I click add column button in my front end).
Now the updated table should be like col1,col2,col3,col4 after altering the fourth column.
Is it possible to alter a column from Frontend? If possible what is the stored procedure/query for that?
From the front-end, you can send the following query.
ALTER TABLE table_name
ADD column_name datatype
For more information on simple Alter statement, , click here:
SQL ALTER TABLE STATEMENT
Hope. This is very helpful.
ALTER TABLE dbo.doc_exy ALTER COLUMN column_a DECIMAL (5, 2) ;

How to change column datatype in SQL Server database without losing data?

I have SQL Server database and I just realized that I can change the type of one of the columns from int to bool.
How can I do that without losing the data that is already entered into that table?
You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumnName BIT
The other option would be to create a new column of type BIT, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..
ALTER TABLE tablename
ALTER COLUMN columnname columndatatype(size)
Note: if there is a size of columns, just write the size also.
If it is a valid change.
you can change the property.
Tools --> Options --> Designers --> Table and Database designers --> Uncheck --> Prevent saving changes that required table re-creation.
Now you can easily change the column name without recreating the table or losing u r records.
if you use T-SQL(MSSQL); you should try this script:
ALTER TABLE [Employee] ALTER COLUMN [Salary] NUMERIC(22,5)
if you use MySQL; you should try this script:
ALTER TABLE [Employee] MODIFY COLUMN [Salary] NUMERIC(22,5)
if you use Oracle; you should try this script:
ALTER TABLE [Employee] MODIFY [Salary] NUMERIC(22,5)
Why do you think you will lose data? Simply go into Management Studio and change the data type. If the existing value can be converted to bool (bit), it will do that. In other words, if "1" maps to true and "0" maps to false in your original field, you'll be fine.
Go to Tool-Option-designers-Table and Database designers and Uncheck Prevent saving option
for me , in sql server 2016, I do it like this
*To rename column Column1 to column2
EXEC sp_rename 'dbo.T_Table1.Column1', 'Column2', 'COLUMN'
*To modify column Type from string to int:( Please be sure that data are in the correct format)
ALTER TABLE dbo.T_Table1 ALTER COLUMN Column2 int;
Alter column data type with check type of column :
IF EXISTS(
SELECT 1
FROM sys.columns
WHERE NAME = 'YourColumnName'
AND [object_id] = OBJECT_ID('dbo.YourTable')
AND TYPE_NAME(system_type_id) = 'int'
)
ALTER TABLE dbo.YourTable ALTER COLUMN YourColumnName BIT
In compact edition will take size automatically for datetime data type i.e. (8) so no need to set size of field and generate error for this operation...
I can modify the table field's datatype, with these following query: and also in the Oracle DB,
ALTER TABLE table_name
MODIFY column_name datatype;
Replace datatype without losing data
alter table tablename modify columnn newdatatype(size);

Convert computed column to regular column

I have a persisted computed column in a large table in in SQL Server 2005.
I want to convert it to a regular column, keeping current values.
Do I have to recreate the column and update the entire table in transaction,
or is it possible to just alter a computed column specification, and how to do it?
-- Create a new Column (unpersisted):
ALTER TABLE MyTable
ADD newColumn DatatypeOfPersistedColumn
GO
UPDATE myTable
SET newColumn = PersistedColumn
GO
-- Delete the persisted column
ALTER TABLE MyTable
DROP COLUMN PersistedColumn
GO
-- Rename new column to old name
EXEC sp_rename 'MyTable.newColumn', 'PersistedColumn', 'COLUMN'
GO
The poster wants to keep the name of the column. I have added a line at the end of Mitch's code to do a rename after dropping the PersistedColumn
-- Create a new Column (unpersisted):
ALTER TABLE MyTable
ADD newColumn DatatypeOfPersistedColumn
UPDATE myTable
SET newColumn = PersistedColumn
-- Delete the persisted column
ALTER TABLE MyTable
DROP COLUMN PersistedColumn
-- Rename the new column to the old name
EXEC sp_rename 'MyTable.newColumn', 'PersistedColumn', 'COLUMN'
#Mitch Wheat's solution works great. However, occasionally this will throw an error with 'Invalid Column name: newColumn' because the table has not been updated before it tries to run the update.
To fix this, add a GO statement to separate the two into batches:
-- Create a new Column (unpersisted):
ALTER TABLE MyTable
ADD newColumn DatatypeOfPersistedColumn
GO
UPDATE myTable
SET newColumn = PersistedColumn
-- Delete the persisted column
ALTER TABLE MyTable
DROP COLUMN PersistedColumn
-- Rename new column to old name
EXEC sp_rename 'MyTable.newColumn', 'PersistedColumn', 'COLUMN'
Assuming that the reason for converting the computed column into a "real" column is that you want to keep the existing values/functionality, but add the ability to override it where desired, you could add a new column (to be populated only where the existing derived value is to be overridden), and change the definition of the computed column to be COALESCE(NewColumn, Old Calculation Definition ) .
Just remove the formula from "Computed Column Specifications" in desing mode of the table in SSMS. The values will stay in column as it is.

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.

Resources