Alter column from NVARCHAR to NBINARY

前提是你 提交于 2020-01-01 16:22:07

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/14305224/alter-column-from-nvarchar-to-nbinary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!