Sql – Change Data Type Varchar To Varbinary(max) In SQL Server

sqlsql server

I want to change varchar to varbinary(max) in SQL Server with this query:

ALTER TABLE  [dbo].[Attachments]
ALTER COLUMN [Content]  varbinary(max)  NOT NULL

but this throws the following exception:

Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query

What should I change in this situation ?

Best Answer

Are you sure you want varbinary(max)? If so, I believe you need to do this in steps:

ALTER TABLE Attachments
ADD Content2 varbinary(max)

UPDATE Attachments
SET Content2 = CONVERT(varbinary(MAX),Content)

ALTER TABLE Attachments
DROP COLUMN Content

sp_RENAME 'Attachments.[Content2]' , '[Content]', 'COLUMN'

Depending on the nature of the table, it might be faster to convert it via a select into:

SELECT Content = CAST(Content AS VARBINARY(MAX))
       ,other fields
INTO NewTable
FROM OldTable

Then drop the old table and rename the new:

DROP TABLE OldTable
GO
SP_RENAME 'NewTable', 'OldTable'