Batch change the char type in all tables in a database to nchar type

Source: Internet
Author: User

/* -- Change the data type of all tables from Char and varchar to nchar and nvarchar.

-- Producer build 2004.02 (reference please keep this information )--*/
 
/* -- Call example:
Exec p_set
--*/
If exists (select * From DBO. sysobjects where id = object_id (n' [DBO]. [p_set] ') and objectproperty (ID, n' isprocedure') = 1)
Drop procedure [DBO]. [p_set]
Go
 
Create procedure p_set
As
Declare TB cursor
Select SQL = 'alter table ['+ D. Name
+ '] Alter column [' + A. Name + '] N'
+ B. Name + '(' + Cast (A. length * 2 as varchar) + ')'
From syscolumns
Left join policypes B on A. xtype = B. xusertype
Inner join sysobjects D on A. ID = D. id and D. xtype = 'U' and D. Name <> 'dtproperties'
Where
B. Name in ('Char ', 'varchar ')
And
Not exists (select 1 from sysobjects where xtype = 'pk' and name in (
Select name from sysindexes where indid in (
Select indid from sysindexkeys where id = A. ID and colid = A. colid
) -- The primary key cannot be modified.
Order by D. Name, A. Name
 
Declare @ SQL varchar (1000)
Open TB
Fetch next from TB into @ SQL
While @ fetch_status = 0
Begin
Exec (@ SQL)
Fetch next from TB into @ SQL
End
Close TB
Deallocate TB
Go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.