Column update - SQL UPDATE statement - sql

I have a column where it stores a reference
the reference is usually 30 alphanumeric values
The column is set as an nvarchar (30).
Id like to update this to nvarchar (5), and update all the values currently stored in this column..
is there a way to do this using update?

First update the table so that you truncate all the column values after the 5th character:
UPDATE tablename SET columnname = LEFT(columnname, 5);
Note, that this may not work if there are constraints on the column (like a unique constraint or foreign key references).
Then change the data type of the column:
ALTER TABLE tablename ALTER COLUMN columnname nvarchar(5);
See a simplified demo.

Should do the trick on SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;

Related

Cannot insert a new column in a table

I have a Product table in which I want to create a new columns Modified_By and Modified_Date_Time. These columns do not allow nulls.
However, as the database already has data, in order to create this column, I had to defined as "allowing nulls". Then, I run a process which updated the new column. The last step was to uncheck the "Allow nulls" property, but when I tried to save the table changes, I got the following error:
'Product_Details' table
- Unable to modify table.
Cannot insert the value NULL into column 'Modified_Date_Time', table 'Vendor Products.dbo.Tmp_Product_Details'; column does not allow nulls. INSERT fails.
The statement has been terminated.
All the rows were succesfully updated with the correct value in the "Modified_By" and "Modified_Date_Time" column, so I don't know why I get this error...Anyway, it seems like a new "temporary" table was created by SQL Server 2008, because I don't have any table with the name "Tmp_Orders"
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
You have to set a default value.
ALTER TABLE Product ADD Modified_By datetime DEFAULT (GETDATE())
The default value will be set to today.
I find the interactive design is not very good at this sort of thing. It's better to simply add the constraint manually
ALTER TABLE Table_Name ALTER COLUMN Column_Name DataType NOT NULL
E.g.
ALTER TABLE MyTable ALTER COLUMN A_Column Int NOT NULL;

Add a column to a table with a default value equal to the value of an existing column

How to add a column to a SQL Server table with a default value that is equal to value of an existing column?
I tried this T-SQL statement:
ALTER TABLE tablename
ADD newcolumn type NOT NULL DEFAULT (oldcolumn)
but it's giving an error:
The name "oldcolumn" is not permitted in this context. Valid
expressions are constants, constant expressions, and (in some
contexts) variables. Column names are not permitted.
Try this:
ALTER TABLE tablename ADD newcolumn type NOT NULL DEFAULT (0)
Go
Update tablename SET newcolumn = oldcolumn Where newcolumn = 0
Go
The AFTER INSERT trigger approach involves overhead due to the extra UPDATE statement. I suggest using an INSTEAD OF INSERT trigger, as follows:
CREATE TRIGGER tablename_on_insert ON tablename
INSTEAD OF INSERT
AS
INSERT INTO tablename (oldcolumn, newcolumn)
SELECT oldcolumn, ISNULL(newcolumn, oldcolumn)
FROM inserted
This does not work though if the oldcolumn is an auto-identity column.
I don't like them very much but here is how you could do this with an AFTER INSERT trigger:
CREATE TRIGGER TableX_AfterInsert_TRG
ON TableX
AFTER INSERT
AS
UPDATE TableX AS t
SET t.newcolumn = t.oldcolumn
FROM Inserted AS i
WHERE t.PK = i.PK ; -- where PK is the PRIMARY KEY of the table
You can use computed column to insert new column in a table based on an existing column value
ALTER TABLE dbo.TableName ADD NewColumn AS (OldColumn) PERSISTED;
OR, if you want to make some changes to the value based on existing column value, use
ALTER TABLE dbo.TableName ADD NewColumn AS (OldColumn * 1.5) PERSISTED;
To extend Kapil's answer, and avoid the unwanted default constraint, try this:
ALTER TABLE tablename ADD newcolumn type NOT NULL CONSTRAINT DF_TMP_TABLENAME_NEWCOLUMN DEFAULT -9999
Go
Update tablename SET newcolumn = oldcolumn
Go
ALTER TABLE tablename DROP CONSTRAINT DF_TMP_TABLENAME_NEWCOLUMN
Go
Replace -9999 by 'noData' if your type is varchar, nvarchar, datetime,... or by any compatible data for other types: specific value doesn't matter, it will be wiped by the 2nd instruction.
For my case, I want to add a new not null unique column named CODE but I don't know about the value at the creation time. I set the default value for it by get a default value from NewID() then update later.
ALTER TABLE [WIDGET] ADD [CODE] CHAR(5) NOT NULL DEFAULT(SUBSTRING(CONVERT(CHAR(36), NEWID()), 1, 5))
ALTER TABLE [dbo].[WIDGET] WITH CHECK ADD CONSTRAINT [UQ_WIDGET_CODE] UNIQUE ([CODE])
Use a computed column, which will even work with IDENTITY column values:
CREATE TABLE #This
( Id INT IDENTITY(1,1)
,MyName VARCHAR(10)
,FullName AS (Myname + CONVERT(VARCHAR(10),Id)) PERSISTED);
INSERT #This VALUES ('Item'),('Item');
SELECT * FROM #This;
DROP TABLE #This;
yields the following:
I think it will work if you use Set Identity_Insert <TableName> OFF and after the insert Statement that you wrote just use Set Identity_Insert <TableName> ON.

Convert bit column to integer

I am converting bit columns of a particular table to integer through an SQL script (this table has some default constraints for default value).
I have to alter the columns for the table, not runtime casting, What script can be used to accomplish this?
Try using CAST(columnName AS INT) AS IntValue.
e.g.
SELECT columnName, CAST(columnName AS INT) AS IntValue
FROM table
OR you can use CONVERT(INT, columnName) AS IntValue.
UPDATE: If you need to alter the actual metadata of the table, then you first need to drop the constraints then alter the column:
i.e.
ALTER TABLE [Table] DROP CONSTRAINT [ConstraintName];
GO
ALTER TABLE [Table] ALTER COLUMN [ColumnName] INT;
Then recreate any constraints that you need.
If you are concerned about changing the datatype of the column you can use an ALTER query as follows.
ALTER TableName ALTER COLUMN ColumnName INT
Else, only for display purposes, you can use either the CAST or CONVERT function:
CAST(columnName AS INT) AS IntegerVal
CONVERT(int, columnName) AS IntValue
None of the provided solutions worked for me. I had to used Signed or Unsigned instead of INT e.g.
SELECT columnName, CAST(columnName AS SIGNED) AS IntValue
FROM table
Hope this helps for new users.
SELECT CONVERT(BIT,'False') AS test1
SELECT CONVERT(BIT,'True') AS test2
We can't simply alter the BIT column to INT. So I suggest to create the new integer column in the table and then using the CAST, update the new integer column with the existing bit values. Then at last you can drop the BIT column from the table.
Finally I managed to get it working:
ALTER TABLE tblname DROP CONSTRAINT DF_tbl_tblname_tblcol
ALTER TABLE tblname ALTER COLUMN tblcol int not null
ALTER TABLE tblname WITH NOCHECK ADD CONSTRAINT [DF_tbl_tblname_tblcol] DEFAULT (0) FOR tblcol
I have used the above SQL statements to alter the table column along with its constructor.
I believe you could extract the bit column as an integer by just using standard CAST() command:
SELECT
CAS(Bit_Column AS int) AS Int_Column
FROM
YourTable
However, I'm not sure I understand what you're trying to achieve, probably you could get a better answer if you provided more details, such as the structure of the table and its constraints.
You are getting an error related to a default constraint. Thus you have to drop that constraint before altering the column data type...
Try this to find all the constraints based on this table (you just need to find the proper default on your column) or use SQL Server Management Studio (SSMS) to generate the script for the table, and this will have the default constraint defintion.
select * from sys.all_objects where parent_object_id = object_id('<tablename>')
go
Then first drop the constraint and then alter the column and add the default again.
alter table bittoint drop constraint DF__bittoint__col2__45D500F0
go
alter table bittoint alter column col2 int
go
alter table bittoint add constraint DF__bittoint__col2__45D500F0 default 0 for col2
go

What is the SQL to change the field length of a table column in SQL Server

What is the SQL to make a field go from nvarchar(50) to nvarchar(250)?
When I try to change it through the SQL Server Management Studio, it doesn't allow me to do it, so I figured I would try SQL directly instead of using the GUI.
Alter table tblname ALTER Column colname nvarchar(250) [NOT] NULL
If NULL / NOT NULL is not specified the column will become Nullable irrespective of what ever the original specification was.
ALTER TABLE MyTable
ALTER COLUMN MyColumn varchar(NewSize)
The ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
My SQL / Oracle (prior version 10G):
ALTER TABLE table_name
MODIFY COLUMN column_name datatype
Oracle 10G and later:
ALTER TABLE table_name
MODIFY column_name datatype
Its sometimes safer to check if the table exist in the first place...
IF COL_LENGTH('[tablename]','[tablecolumn]') IS NULL
BEGIN
ALTER TABLE tablename
ALTER COLUMN [tablecolumn]
NVARCHAR(500)
END
To change the datatype of many column but same datatype
alter table employee modify (firstname varchar2(9),lastname varchar2(9),email varchar2(9));
-- Table altered.
alter table employee modify (firstname,lastname,email varchar2(9));
-- Table altered.
For Oracle SQL Developers
Alter table tblname MODIFY (colname varchar2(250));
Description : It will increase the length of column. where 250
represent the updated (incremented) length of column.

Can I add a not null column without DEFAULT value

Can I add a column which is I specify as NOT NULL,I don't want to specify the DEFAULT value but MS-SQL 2005 says:
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'test' cannot be added to non-empty table 'shiplist' because it does not satisfy these conditions.
If YES, please let me know the syntax, if No please specify the reason.
No, you can't.
Because if you could, SQL wouldn't know what to put as value in the already existing records. If you didn't have any records in the table it would work without issues.
The simplest way to do this is create the column with a default and then remove the default.
ALTER TABLE dbo.MyTable ADD
MyColumn text NOT NULL CONSTRAINT DF_MyTable_MyColumn DEFAULT 'defaultValue'
ALTER TABLE dbo.MyTable
DROP CONSTRAINT DF_MyTable_MyColumn
Another alternative would be to add the column without the constraint, fill the values for all cells and add the constraint.
Add the column to the table, update the existing rows so none of them are null, and then add a "not null" constraint.
No - SQL Server quite reasonably rejects this, because it wouldn't know what value existing rows should have
It's easy to create a DEFAULT at the same time, and then immediately drop it.
I use this approach to insert NOT NULL column without default value
ALTER TABLE [Table] ADD [Column] INT NULL
GO
UPDATE [Table] SET [Column] = <default_value>
ALTER TABLE [Table] ALTER COLUMN [Column] INT NOT NULL
No.
Just use empty string '' (in case of character type) or 0 (if numeric), etc as DEFAULT value
No you cannot. But you can consider to specify the default value to ('')
No, you can't, as SQL Server, or any other database engines will force this new column to be null for existing rows into your data table. But since you do not allow a NULL, you are required to provide a default value in order to respect your own constraint. This falls under great sense! The DBE will not extrapolate a value for non-null values for the existing rows.
#Damien_The_Unbeliever's comment ,
Is it adding computed column? Neither question nor answer implied anything like that. In case of computed column the error states:
"Only UNIQUE or PRIMARY KEY constraints can be created on computed columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require that computed columns be persisted"
OK, if to continue this guessing game, here is my script illustrating the adding of "NOT NULL" column in one "ALTER TABLE" step:
CREATE TABLE TestInsertComputedColumn
(
FirstName VARCHAR(100),
LastName CHAR(50)
);
insert into TestInsertComputedColumn(FirstName,LastName)
select 'v', 'gv8';
select * from TestInsertComputedColumn;
ALTER TABLE TestInsertComputedColumn
ADD FullName As FirstName + LastName PERSISTED NOT NULL;
select * from TestInsertComputedColumn;
--drop TABLE TestInsertComputedColumn;
I used below approach it worked for me
Syntax:
ALTER TABLE <YourTable> ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
Example:
ALTER TABLE Tablename ADD ColumnName datetime NOT NULL DEFAULT GETDATE();
As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO