Monday, March 19, 2012

Alter Table - Change Column Datatype

Hi,

I want to change the datatype of an existing column from char to
varbinary. When I run the "Alter Table" statement, I get the
following error message -

Disallowed implicit conversion from data type char to data type
varbinary, table 'test.dbo.testalter', column 'col1'. Use the CONVERT
function to run this query.

Can the CONVERT function be used as part of an alter table/alter
column? Is there another way besides renaming the table and creating
a new one?

Thanks,
BruceOn 19 Apr 2004 11:29:46 -0700, Bruce wrote:

>Hi,
>I want to change the datatype of an existing column from char to
>varbinary. When I run the "Alter Table" statement, I get the
>following error message -
>Disallowed implicit conversion from data type char to data type
>varbinary, table 'test.dbo.testalter', column 'col1'. Use the CONVERT
>function to run this query.
>Can the CONVERT function be used as part of an alter table/alter
>column? Is there another way besides renaming the table and creating
>a new one?
>Thanks,
>Bruce

Yes, there is another way: rename not the whole table, but just the
column, then create a new one:

EXEC sp_rename 'test.dbo.testalter.col1' 'col1old', COLUMN
go
ALTER TABLE test.dbo.testalter
ADD col1 varbinary(321) NULL
-- If it has to be NOT NULL, change this to read
-- ADD col1 varbinary(321) NOT NULL DEFAULT 0
go
UPDATE test.dbo.testalter
SET col1 = CAST(col1old AS varbinary(321))
go
ALTER TABLE test.dbo.testalter
DROP COLUMN col1old
go

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)

No comments:

Post a Comment