Home All Groups Group Topic Archive Search About

Bulk Convert Data Type in Database

Author
25 Aug 2006 5:06 PM
AmytDev
Would anyone know how I could update a data type from nvarchar to varchar for
an entire database of tables? I don't want to have to manually open each
table and replace the field data types. Please advise.

Amytdev

Author
25 Aug 2006 7:46 PM
PCTC_IT
I would add a new varchar column, copy the data from the nvarchar colum into
the new column, drop old column, and rename it.

Something like this:
UPDATE myTable SET NewColumn = oldcolumn
Drop your column, and rename the new one


Show quote
"AmytDev" wrote:

> Would anyone know how I could update a data type from nvarchar to varchar for
> an entire database of tables? I don't want to have to manually open each
> table and replace the field data types. Please advise.
>
> Amytdev
Author
26 Aug 2006 9:40 PM
Erland Sommarskog
AmytDev (Amyt***@discussions.microsoft.com) writes:
> Would anyone know how I could update a data type from nvarchar to
> varchar for an entire database of tables? I don't want to have to
> manually open each table and replace the field data types. Please
> advise.

   SELECT 'ALTER TABLE ' + o.name + ' ALTER COLUMN ' + c.name +
           ' nvarchar(' + ltrim(str(c.length)) + ') ' +
           CASE columnproperty(c.id, c.name, 'AllowsNull')
                WHEN 1 THEN ''
                WHEN 0 THEN 'NOT '
           END + 'NULL'
   FROM   sysobjects o
   JOIN   syscolumns c ON o.id = c.id
   WHERE  type_name(c.xtype) = 'varchar'
     AND  o.type = 'U'

Copy and paste result into a query window and run. In practice it is
not going to be this easy, you will first need to drop all indexes,
primary and foreign key and probably also check constraints and defaults.

So the best option may be to script the database and then run a replace
tool on it to change all occurrences of varchar to nvarchar. This also
handles stored procedures which may have variables and temp tables with
varchar.



--
Erland Sommarskog, SQL Server MVP, esq***@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

AddThis Social Bookmark Button