Adding a column after another column within SQL - sql

How do I add a column after another column within MS SQL by using SQL query?
TempTable
ID int,
Type nvarchar(20),
Active bit
NewTable
ID int,
Type nvarchar(20),
Description text,
Active bit
That is what I want, how do I do that

Assuming MySQL (EDIT: posted before the SQL variant was supplied):
ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn
The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:
ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:
ALTER TABLE name ALTER column POSITION new_position
I guess it may work in other cases as well.

Related

Changing the data type "varchar'' of a column to "DATE" in SQL/ORACLE

I have a table in a database created in oracle 10G. It contains a column of type 'VARCHAR' and stores date as string in this format-> 'dd-mon-yyyy' eg: '12-aug-2008'. Now I want to change the datatype of this column from VARCHAR to DATE. but when i perfrom this query->
ALTER TABLE sales_order
MODIFY COLUMN delivery_date DATE;
I get following error
ORA-00905: missing keyword
I have also tried :
ALTER TABLE sales_order
ALTER COLUMN delivery_date DATE;
I got the error :
ORA-01735: invalid ALTER TABLE option
However when i try to add a fresh column with DATE datatype it works fine.
example :
ALTER TABLE sales_order
ADD delivery DATE;
So, can anybody suggest me a way to change the datatype without deleting the column and its data.
It's the first one, with a slight modification:
ALTER TABLE sales_order MODIFY (delivery_date DATE);
But I'm not sure that will work for those particular datatypes and it also may not work depending on the current data.
You may find it necessary in that case to:
create a new column X of date type.
populate X based on the old column (may need several passes of data fix-ups to work).
delete old column.
rename X to old column name.
Although its a pretty old question, I'll put my solution here for people seeking for a solution:
Here's my solution and it works perfectly.
ALTER TABLE `sales_order` CHANGE `delivery_date` `delivery_date` DATE;
Thank you
modify a column then syntax is:-
alter table table_name modify column_name datatype;
but when you modify the column datatype column must be empty
Thanks for the hints! This got it for me.
alter table Table_Name
Alter column Column_Name datatype
GO
I too was needing to change from a VARCHAR to a date. I am working in SQL 2008 R2. I have found that if I bring in dates as a char or varchar and then change the type to date or datetime, I can catch time/date problems more easily.
THIS STATEMENT WILL FAIL IF YOUR DATA HAS ANY BAD DATES. (I break the date down into sections to find the bad date so I can correct and then I can alter the column type.)
Alternatively, you could create a new column, in which the data type is DATE. then pass the data in your varchar as a date .then drop your initial column and finally rename your new column to what it was initially...code below.
ALTER TABLE my_table ADD (new_col DATE);
UPDATE my_table SET new_col=TO_DATE(old_col,'MM/DD/YYYY');
ALTER TABLE my_table DROP (old_col);
ALTER TABLE my_table RENAME COLUMN new_col TO old_col;
alter table employee add (DOB varchar(10));
if you add a column with datatype varchar and if you want to modify the datatype of DOB then you can use this command ->
alter table employee modify(DOB date);
Now the table is modified.

Change column type without losing data

I am working on an SQL Database, I have a column named "Price". When the database was created the column "Price" was set to NVARCHAR I need to change its type to decimal(18, 2) without losing the data in the database. This should be done by an SQL Script
I thought of creating a new column, moving the data to it, remove the old column, and then rename the newly created column.
Can someone help me with an example on how to do this?
Also is there a function in SQL to Parse string to decimal?
Thanks
You don't need to add a new column two times, just remove the old one after updating the new one:
ALTER TABLE table_name ADD new_column_name decimal(18,2)
update table_name
set new_column_name = convert(decimal(18,2), old_column_name)
ALTER TABLE table_name DROP COLUMN old_column_name
Note that if the old_column_name is not numeric, the convert may fail.
Something Like
Alter Table [MyTable] Add Column NewPrice decimal(18,2) null
Then
Update [MyTable] Set NewPrice = Convert(decimal(18,2),[Price]) Where Price is not null
If the above fails then you'll need to beef it up to deal with the funnies
Once you are happy drop the old column with an Alter Table and rename the new one with sp_rename
If you just want to change only column's data type, you can do like this=>
Alter Table YourTableName
Alter Column ColumnName DataType
I already test this on SQL server 2012 and its work.
You can make those changes visually using Management Studio. Then, use the button "Generate Change Script" to get the script for the changes you made. Be sure to do all testing in a copy of the original ddbb, in case something goes wrong..

SQL server 2005 query not running

Before posting this question, I have tried so many things but that was not helpful for me.
I want to rename the column of table at sql server 2005, following query I have run at sql server2005:
1) ALTER TABLE Details RENAME COLUMN
AccountID TO UID; but it gives me the
error: Incorrect syntax near the
keyword 'COLUMN'.
2)I have added one new column in the
table by query: ALTER TABLE Details
ADD BID uniqueidentifier; and then I
want to set the coulmn property to not
null .
How can i do that?
Thanks in advance
AS
Use sp_Rename 'TableName.Column', 'NewColumnName', 'COLUMN'.
In order to do your second part of the question, you'll need to do:
ALTER TABLE myTable
ADD myColumn UNIQUEIDENTIFIER NOT NULL DEFAULT 'some default value'
If you don't want to specify a default value, you'll have to first create the column with NULL. Once the column is created, you can then populate with your desired values and then re-alter the column to NOT NULL.
1) Instead of using ALTER TABLE, why not use sp_rename? For example:
EXEC sp_rename 'Details.[AccountID]', 'title', 'UID'
2) You can use ALTER TABLE Details ALTER COLUMN BID NOT NULL, but you'll probably want to specify a default value for it also, if the table already has data in it.

Altering a Table Column to Accept More Characters

What would the command be for Microsoft SQL Server 2008 to alter an existing column to allow for more characters? Would this have an effect on any previous entries in the column if I'm only expanding it?
I have a URL column that I need to add about 100 characters to.
ALTER TABLE [table] ALTER COLUMN [column] NVARCHAR(newsize)
And increasing the size won't affect your data.
ALTER TABLE myTable ALTER COLUMN myColumn varchar(100)
GO
This would not involve the risk of losing data, because you are expanding the size of the column.
ALTER TABLE tab ALTER COLUMN c VARCHAR(200)
You can use SQL Server Management Studio to generate the code to do this yourself. Just modify the table in the designer so that the column is wider and click "Generate change script" (under the "Table designer" menu).
Depending on the change you make the code to modify a table can be fairly complex.
It is quite simple:
ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(100)

How do I rename a column in a database table using SQL?

If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that? Or is it not possible?
This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation.
Specifically for SQL Server, use sp_rename
USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO
On PostgreSQL (and many other RDBMS), you can do it with regular ALTER TABLE statement:
=> SELECT * FROM Test1;
id | foo | bar
----+-----+-----
2 | 1 | 2
=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE
=> SELECT * FROM Test1;
id | baz | bar
----+-----+-----
2 | 1 | 2
In MySQL, the syntax is ALTER TABLE ... CHANGE:
ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <data_type> ...
Note that you can't just rename and leave the type and constraints as is; you must retype the data type and constraints after the new name of the column.
Unfortunately, for a database independent solution, you will need to know everything about the column. If it is used in other tables as a foreign key, they will need to be modified as well.
ALTER TABLE MyTable ADD MyNewColumn OLD_COLUMN_TYPE;
UPDATE MyTable SET MyNewColumn = MyOldColumn;
-- add all necessary triggers and constraints to the new column...
-- update all foreign key usages to point to the new column...
ALTER TABLE MyTable DROP COLUMN MyOldColumn;
For the very simplest of cases (no constraints, triggers, indexes or keys), it will take the above 3 lines. For anything more complicated it can get very messy as you fill in the missing parts.
However, as mentioned above, there are simpler database specific methods if you know which database you need to modify ahead of time.
I think this is the easiest way to change column name.
SP_RENAME 'TABLE_NAME.OLD_COLUMN_NAME','NEW_COLUMN_NAME'
In sql server you can use
exec sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'
or
sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'
In Informix, you can use:
RENAME COLUMN TableName.OldName TO NewName;
This was implemented before the SQL standard addressed the issue - if it is addressed in the SQL standard. My copy of the SQL 9075:2003 standard does not show it as being standard (amongst other things, RENAME is not one of the keywords). I don't know whether it is actually in SQL 9075:2008.
You can use the following command to rename the column of any table in SQL Server:
exec sp_rename 'TableName.OldColumnName', 'New colunmName'
ALTER TABLE is standard SQL. But it's not completely implemented in many database systems.
The standard would be ALTER TABLE, but that's not necessarily supported by every DBMS you're likely to encounter, so if you're looking for an all-encompassing syntax, you may be out of luck.
Alternatively to SQL, you can do this in Microsoft SQL Server Management Studio, from the table Design Panel.
First Way
Slow double-click on the column. The column name will become an editable text box.
Second Way
SqlManagement Studio>>DataBases>>tables>>specificTable>>Column
Folder>>Right Click on column>>Reman
Third Way
Table>>RightClick>>Design
To rename you have to change the column
e.g
Suppose
*registration is Table Name
newRefereeName is a column name That I want to change to refereeName
SO my SQL Query will be*
ALTER TABLE 'registration' CHANGE 'newRefereeName' 'refereeName' VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL;
exec sp_rename 'Tablename.OldColumnName', 'NewColumnName', 'Column';