Alter column from NVARCHAR to NBINARY - sql-server

I accidentally created a column with the wrong type NVARCHAR (for storing password salts) and I want to convert it to NVARBINARY.
I tried
ALTER TABLE [dbo].[TableName]
ALTER COLUMN [ColumnName] [varbinary] (20) NOT NULL
GO
but it says
Implicit conversion from data type nvarchar to varbinary is not allowed. Use the CONVERT function to run this query.
Is there a way to do that? CONVERT seems to be for expressions only, not for alterations.

The only way by altering will be someting like:
Create Table a (id int,blb Nvarchar(10))
insert into a Values
(1,'Test'),
(2,N'Test2');
BEGIN Transaction
ALTER TABLE a
ADD blb_New [varbinary] (20) NULL
GO
UPDATE a
SET blb_new = CAST(blb AS varbinary(20))
GO
ALTER TABLE a
DROP COLUMN blb
GO
EXEC sp_rename 'a.blb_new', 'blb', 'COLUMN'
GO
COMMIT Transaction
Select *,CAST(blb as Nvarchar(20)) from a
Drop Table a

You may first convert all the values from NVARCHAR to NVARBINARY in the same column.
After converting all the values use Alter table
You may refer the following link:
Converting NVARCHAR(255) to DATE

Related

How to change datatype VARCHAR to DATETIME?

My current Database column's datatype is varchar, but I want to alter it to datetime. I use this sqlserver code to alter it, but failed.
ALTER TABLE Logbook
ALTER COLUMN Company_Date datetime NOT NULL;
Result:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
The easiest option here might be to use TRY_CONVERT:
ALTER TABLE Logbook ADD COLUMN Company_Date1 datetime;
UPDATE Logbook
SET Company_Date1 = TRY_CONVERT(datetime, Company_Date);
ALTER TABLE Logbook DROP COLUMN Company_Date;
sp_rename 'Logbook.Company_Date1', 'Company_Date', 'COLUMN';
The strategy here is to create a new datetime column Company_Date1 which is a bona fide datetime column. Then, we update it using TRY_CONVERT against the text values in Company_Date. Note that should the conversion not be possible, there would be no error, but instead a NULL would be returned. Finally we drop the original text Company_Date column and rename Company_Date1 to Company_Date.
you have some bad data in column one way you can use isdate function before alter column such as
update logbook set company_date=null where isdate(company_date)=0
after that alter column
another way select the list of bad data and correct it then alter column

I need to update my table by converting a column from int into date in sql server

I want to update the column transe_date from int into date ..
update fci
set fci.transe_date= convert(date,convert(varchar(8),transe_date));
Rather than creating a new column, completing an UPDATE statement, renaming your old column, and then the new, you could use 2 ALTER statements. You can't implicity convert an int to date, but you can implicitly convert an int to varchar and then from a varchar to a date:
USE Sandbox;
GO
CREATE TABLE dbo.SomeTable (DateColumn int);
INSERT INTO dbo.SomeTable (DateColumn)
VALUES (20160101),
(20160307),
(20180920);
GO
SELECT *
FROM dbo.SomeTable
GO
ALTER TABLE dbo.SomeTable ALTER COLUMN DateColumn varchar(8);
ALTER TABLE dbo.SomeTable ALTER COLUMN DateColumn date;
GO
SELECT *
FROM dbo.SomeTable
GO
DROP TABLE dbo.SomeTable
Of course, this assumes that all your ints are valid date values.
Edit: If you do have values that aren't valid date values, you'll need to identify and correct these first. You could identify these by using TRY_CONVERT:
SELECT YourIntColumn
FROM dbo.YourTable
WHERE TRY_CONVERT(date,CONVERT(varchar(11),YourIntColumn)) IS NULL;
There's no need to put a TRY_CONVERT on the varchar(11), as an int can always be converted to a varchar. I used varchar(11) as well (instead of varchar(8)( because the largest value, in character length, you could have would be -2147483648 (which is 11 characters long).
Make a dummy column to hold data
Change data type of existing column
put all values back after converting using the column made
Drop the dummy column
Cleaning the new column
Script sample will be
/*1*/
Alter Table FCI
Add tempcol DateTime
Go
/*2*/
update fci
set tempcol = convert(date,convert(varchar(8),transe_date));
/*3*/
Alter Table FCI
alter column transe_date DateTime
Go
/*4*/
update fci
set transe_date = tempcol;
/*5*/
Alter Table FCI
drop column tempcol
Go
If the whole data is Date then directly converting the column type can do the job, the above process is the safe side process for start.
If you want to convert the int values into dates, you will first have to add a new column (transe_date2) of that type. Then, you can store the converted values in this new column:
update fci
set fci.transe_date2 = convert(date,convert(varchar(8),transe_date));
Having done this, I suggest to use SSMS to drop the old column and rename the new one.
Here are the steps:
--add date column
ALTER TABLE fci ADD transe_date2 date;
GO
--do conversions
UPDATE fci SET transe_date2=CONVERT(date,CONVERT(varchar(8),transe_date),112);
GO
--drop int column
ALTER TABLE fci DROP COLUMN transe_date;
GO
--rename temporary column to transe_date
EXEC sp_rename 'fci.transe_date2', 'transe_date', 'COLUMN';

ALTER TABLE ALTER COLUMN "Present _Address" failed because one or more objects access this column

I have a database where I have to convert all varchar datatype columns to nvarchar type. I have been able to convert all tables except one. Before converting into nvarchar datatype I am dropping all constraints like foreign key, primary key, unique key, check constraints, default constraints and indexes. I also have deleted all the data before altering to nvarchar.
The problem is that I am getting the error
ALTER TABLE ALTER COLUMN "Permanent Address" failed because one or more objects access this column.
when I am executing the drop and create table statements it is working there but while converting to nvarchar with ALTER command I am getting the error
I have the following scripts
--The actual table deifinition
USE [Customer]
GO
--Permanent_Address is a computed column
CREATE TABLE [dbo].[Customer_Contact](
[Customer_id] int NOT NULL,
[Present_Address] [varchar](250) NOT NULL,
[Permanent_Address] AS ([Present_Address]))
--Alter statement to convert from varchar to nvarchar
ALTER TABLE [Customer_Contact] ALTER COLUMN [Present Address] NVARCHAR(250) NOT NULL
ALTER TABLE [Customer_Contact] ALTER COLUMN [Permanent_Address] NVARCHAR(250) NOT NULL
Result-: ALTER TABLE ALTER COLUMN "Permanent Address" failed because one or more objects access this column.
--Drop and Create the table script
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Customer_Contact]') AND type in (N'U'))
DROP TABLE [dbo].[Customer_Contact]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer_Contact](
[Customer_id] int NOT NULL,
[Present_Address] [Nvarchar](250) NOT NULL,
[Permanent_Address] AS ([Present_Address]))
--The table is created successfully with Nvarchar Datatype

SQL alter column datatype from nvarchar to int

Can the datatype of a field be changed to int from nvarchar??
alter table employee alter column designation int
is this valid?? If not can it be done in some other way??
P.S: I am using MS SQL Server
You can try doing an alter table. If it fails do this:
Create a new column that's an integer:
ALTER TABLE tableName ADD newCol int;
Select the data from the old column into the new one:
UPDATE tableName SET newCol = CAST(oldCol AS int);
Drop the old column
It is possible only when you column has no value or blank. If your column has some value which have nvarchar value and you should try to convert it into int, it will give error.
ALTER TABLE [table_name] ALTER COLUMN [column_name] [data_type]
Add new numeric column.
Copy from old char column to new column with trim and conversion.
Drop old char column.
Rename numeric column to old column name.
This worked for me (with decimals but I suppose it will work with ints):
alter table MyTable add MyColNum decimal(15,2) null
go
update MyTable set MyColNum=CONVERT(decimal(15,2), REPLACE(LTRIM(RTRIM(MyOldCol)), ',', '.')) where ISNUMERIC(MyOldCol)=1
go
alter table MyTable drop column MyOldCol
go
EXEC sp_rename 'MyTable.MyColNum', 'MyOldCol', 'COLUMN'
go
Can be done even simpler in just 2 steps
Update the column and set all non numberic values to null so alter won't fail.
Alter the table and set the type to int.
UPDATE employee
SET designation = (CASE WHEN ISNUMERIC(designation)=1 THEN CAST(CAST(designation AS FLOAT) AS INT)END )
ALTER TABLE employee
ALTER COLUMN designation INT
This takes the assumption that that the columns allow nulls. If not then that needs to be handled as well. For example: By altering the column to allow null, then after it has been converted to int then set all null values to 0 and alter the table to not allow null
Create a temp column
ALTER TABLE MYTABLE ADD MYNEWCOLUMN NUMBER(20,0) NULL;
Copy and casts the data from the old column to the new one
UPDATE MYTABLE SET MYNEWCOLUMN=CAST(MYOLDCOLUMN AS NUMBER(20,0));
Delete the old column
ALTER TABLE MYTABLE DROP COLUMN MYOLDCOLUMN;
Rename the new one to match the same name as the old one.
ALTER TABLE MYTABLE RENAME COLUMN MYNEWCOLUMN TO MYOLDCOLUMN;
Can you try this ?
alter table MyTable add MyColNum Varchar(500) null;
alter table MyTable add MyColNum int null;

Change column from VARCHAR(MAX) to VARBINARY(MAX)

I have a table which has a VARCHAR(MAX) column, and I need to change it to VARBINARY(MAX).
I tried using the command
ALTER TABLE TableName ALTER COLUMN ColumnName VARBINARY(MAX)
but I got the error
Msg 257, Level 16, State 3, Line 1
Implicit conversion from data type varchar(max) to varbinary(max) is not allowed.
Use the CONVERT function to run this query.
The table has no data, so I can't understand why it's complaining about data conversion.
You cannot perform this conversion using an ALTER TABLE statement since converting from varchar(max) to varbinary(max) requires an explicit conversion. So you should follow these steps to alter your table:
Alter table with new column of VARBINARY(MAX)
If you have existing data in the VARCHAR(MAX) column, use update statement to add the data to the VARBINARY column
Alter table to drop the VARCHAR(MAX) column
Rename varbinary column to varchar name (per comment from #Ben Thul)
Convert Varchar to Int and then change Int to Binary.

Resources