This info is from: http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Have you encountered a problem where you wanted to change your database collation to default or even just change it to a different type? I guess what you had initially done (like me) was to change the collation of the database.

Well, that does not quite work well as the existing columns will not be changed and retain its current collation type, only the newly created objects will use this new collation type. So you are left to the option of changing the columns one at a time by going to the column property and restoring it to default, or choosing the collation type you want.

Well, that’s great if you need to change 10 columns or less but what if you want to change the whole database? What if it’s a primary key or a foreign key? Well, isn’t that a nightmare? Well, I will give you an easy solution and all you need to do is to run 6 easy steps. If you don’t want to recreate the database and pump data by using DTS or SSIS, then this is the solution for you; just make sure to backup and restore everything before doing any changes.

Step 1: Prepare your DB and change the collation to your desired one

Like I had said, backup your database as a part of the preparation. Once that’s done, change your collation to the desired type by going to the database properties by right clicking on the database and choosing properties. Once you are on the Properties window, choose options and you can see the collation from there, choose what you want, then hit OK. This will ensure that new objects created will be using the new collation.

Step 2: Create you Change Collation Script.

Next is to create a script to change the collation of every object in your database. You need to use information_schema to extract columns needed to be changed and from there we run a loop on all objects creating alter scripts on each item. Since it is a collation change, we will only need fields that uses character types and text types. What you need is to have a lot of commands similar to this.

ALTER TABLE TABLENAME ALTER COLUMN COLUMNNAME varchar(100) COLLATE Latin1_General_CI_AS NULL

So here is the code to generate that:

OPEN MyTableCursor

FETCH NEXT FROM MyTableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE MyColumnCursor Cursor
FOR
SELECT COLUMN_NAME,DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
IS_NULLABLE from information_schema.columns
WHERE table_name = @TableName AND (Data_Type LIKE '%char%'
OR Data_Type LIKE '%text%') AND COLLATION_NAME <> @CollationName
ORDER BY ordinal_position
Open MyColumnCursor FETCH NEXT FROM MyColumnCursor INTO @ColumnName, @DataType,
@CharacterMaxLen, @IsNullable
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQLText = 'ALTER TABLE ' + @TableName + ' ALTER COLUMN [' + @ColumnName + '] ' +
@DataType + '(' + CASE WHEN @CharacterMaxLen = -1 THEN 'MAX' ELSE @CharacterMaxLen END +
') COLLATE ' + @CollationName + ' ' +
CASE WHEN @IsNullable = 'NO' THEN 'NOT NULL' ELSE 'NULL' END
PRINT @SQLText FETCH NEXT FROM MyColumnCursor INTO @ColumnName, @DataType,
@CharacterMaxLen, @IsNullable
END
CLOSE MyColumnCursor
DEALLOCATE MyColumnCursor FETCH NEXT FROM MyTableCursor INTO @TableName
END
CLOSE MyTableCursor
DEALLOCATE MyTableCursor

Run it then save the script for later use. Let us call the script “ChangeCollation.sql”.

If you don’t have relationships, primary keys, and foreign keys then you don’t need to do the next step.

Step 3: Create a Stored Procedure to Script Indexes and Relationships

Well, if you have relationships, primary keys, and foreign keys, then that’s a good practice but you need to script them as you need to drop those before changing the collation. Initially, I thought I can do this with the wizard and choose to script indexes but it does not create on its own the table creation is always included so with a little help from Google, I don’t have to write a single piece of code. I found this really good script to do it and I got it from here:http://sqlblog.com/blogs/adam_machanic/archive/2010/04/04/rejuvinated-script-creates-and-drops-for-candidate-keys-and-referencing-foreign-keys.aspx.

I only separated the Create Indexes and Drop Indexes as we need to run a process in the middle.

Here is the Create Index script, courtesy of Adam Machanic:

/*
Script Table Keys
(C) 2010 Adam Machanic - amachanic@gmail.com
http://sqlblog.com/blogs/adam_machanic/archive/2010/04/04/
rejuvinated-script-creates-and-drops-for-candidate-keys
-and-referencing-foreign-keys.aspx
This script produces a script of all of the candidate keys (primary keys or unique
constraints) as well as referencing foreign keys, for the target table. To use, put
SSMS into "results in text" mode and run the script. The output will be a formatted
script that you can cut and paste to use elsewhere. Don't forget to configure the maximum text size before using. The default is 256
characters--not enough for many cases. Tools->Options->Query Results->Results to Text->Maximum number of characters->8192
*/
CREATE PROC [dbo].[ScriptCreateTableKeys]
@table_name SYSNAME
AS
BEGIN
SET NOCOUNT ON --Note: Disabled keys and constraints are ignored
--TODO: Drop and re-create referencing XML indexes, FTS catalogs DECLARE @crlf CHAR(2)
SET @crlf = CHAR(13) + CHAR(10)
DECLARE @version CHAR(4)
SET @version = SUBSTRING(@@VERSION, LEN('Microsoft SQL Server') + 2, 4)
DECLARE @object_id INT
SET @object_id = OBJECT_ID(@table_name)
DECLARE @sql NVARCHAR(MAX) IF @version NOT IN ('', '')
BEGIN
RAISERROR('This script only supports SQL Server 2005 and 2008', 16, 1)
RETURN
END SET @sql = '' +
'SELECT ' +
'CASE ' +
'WHEN 1 IN (i.is_primary_key, i.is_unique_constraint) THEN ' +
'''ALTER TABLE '' + ' +
'QUOTENAME(OBJECT_SCHEMA_NAME(i.object_id)) + ''.'' + ' +
'QUOTENAME(OBJECT_NAME(i.object_id)) + @crlf + ' +
'''ADD '' + ' +
'CASE k.is_system_named ' +
'WHEN 0 THEN ''CONSTRAINT '' + QUOTENAME(k.name) + @crlf ' +
'ELSE '''' ' +
'END + ' +
'CASE k.type ' +
'WHEN ''UQ'' THEN ''UNIQUE'' ' +
'ELSE ''PRIMARY KEY'' ' +
'END + '' '' + ' +
'i.type_desc + @crlf + ' +
'kc.key_columns + @crlf ' +
'ELSE ' +
'''CREATE UNIQUE '' + i.type_desc + '' INDEX '' + ' +
'QUOTENAME(i.name) + @crlf + ' +
'''ON '' + ' +
'QUOTENAME(OBJECT_SCHEMA_NAME(i.object_id)) + ''.'' + ' +
'QUOTENAME(OBJECT_NAME(i.object_id)) + @crlf + ' +
'kc.key_columns + @crlf + ' +
'COALESCE ' +
'( ' +
'''INCLUDE '' + @crlf + ' +
'''( '' + @crlf + ' +
'STUFF ' +
'( ' +
'( ' +
'SELECT ' +
'( ' +
'SELECT ' +
''','' + @crlf + '' '' + QUOTENAME(c.name) AS [text()] ' +
'FROM sys.index_columns AS ic ' +
'JOIN sys.columns AS c ON ' +
'c.object_id = ic.object_id ' +
'AND c.column_id = ic.column_id ' +
'WHERE ' +
'ic.object_id = i.object_id ' +
'AND ic.index_id = i.index_id ' +
'AND ic.is_included_column = 1 ' +
'ORDER BY ' +
'ic.key_ordinal ' +
'FOR XML PATH(''''), TYPE ' +
').value(''.'', ''VARCHAR(MAX)'') ' +
'), ' +
'1, ' +
'3, ' +
''''' ' +
') + @crlf + ' +
''')'' + @crlf, ' +
''''' ' +
') ' +
'END + ' +
'''WITH '' + @crlf + ' +
'''('' + @crlf + ' +
''' PAD_INDEX = '' + ' +
'CASE CONVERT(VARCHAR, i.is_padded) ' +
'WHEN 1 THEN ''ON'' ' +
'ELSE ''OFF'' ' +
'END + '','' + @crlf + ' +
'CASE i.fill_factor ' +
'WHEN 0 THEN '''' ' +
'ELSE ' +
''' FILLFACTOR = '' + ' +
'CONVERT(VARCHAR, i.fill_factor) + '','' + @crlf ' +
'END + ' +
''' IGNORE_DUP_KEY = '' + ' +
'CASE CONVERT(VARCHAR, i.ignore_dup_key) ' +
'WHEN 1 THEN ''ON'' ' +
'ELSE ''OFF'' ' +
'END + '','' + @crlf + ' +
''' ALLOW_ROW_LOCKS = '' + ' +
'CASE CONVERT(VARCHAR, i.allow_row_locks) ' +
'WHEN 1 THEN ''ON'' ' +
'ELSE ''OFF'' ' +
'END + '','' + @crlf + ' +
''' ALLOW_PAGE_LOCKS = '' + ' +
'CASE CONVERT(VARCHAR, i.allow_page_locks) ' +
'WHEN 1 THEN ''ON'' ' +
'ELSE ''OFF'' ' +
'END + ' +
CASE @version
WHEN '' THEN ''
ELSE
''','' + @crlf + ' +
''' DATA_COMPRESSION = '' + ' +
'( ' +
'SELECT ' +
'CASE ' +
'WHEN MIN(p.data_compression_desc) =
MAX(p.data_compression_desc)
THEN MAX(p.data_compression_desc) ' +
'ELSE ''[PARTITIONS USE
MULTIPLE COMPRESSION TYPES]'' ' +
'END ' +
'FROM sys.partitions AS p ' +
'WHERE ' +
'p.object_id = i.object_id ' +
'AND p.index_id = i.index_id ' +
') '
END + '+ @crlf + ' +
''') '' + @crlf + ' +
'''ON '' + ds.data_space + '';'' + ' +
'@crlf + @crlf COLLATE database_default AS [-- Create Candidate Keys] ' +
'FROM sys.indexes AS i ' +
'LEFT OUTER JOIN sys.key_constraints AS k ON ' +
'k.parent_object_id = i.object_id ' +
'AND k.unique_index_id = i.index_id ' +
'CROSS APPLY ' +
'( ' +
'SELECT ' +
'''( '' + @crlf + ' +
'STUFF ' +
'( ' +
'( ' +
'SELECT ' +
'( ' +
'SELECT ' +
''','' + @crlf + '' '' + QUOTENAME(c.name) AS [text()] ' +
'FROM sys.index_columns AS ic ' +
'JOIN sys.columns AS c ON ' +
'c.object_id = ic.object_id ' +
'AND c.column_id = ic.column_id ' +
'WHERE ' +
'ic.object_id = i.object_id ' +
'AND ic.index_id = i.index_id ' +
'AND ic.key_ordinal > 0 ' +
'ORDER BY ' +
'ic.key_ordinal ' +
'FOR XML PATH(''''), TYPE ' +
').value(''.'', ''VARCHAR(MAX)'') ' +
'), ' +
'1, ' +
'3, ' +
''''' ' +
') + @crlf + ' +
''')'' ' +
') AS kc (key_columns) ' +
'CROSS APPLY ' +
'( ' +
'SELECT ' +
'QUOTENAME(d.name) + ' +
'CASE d.type ' +
'WHEN ''PS'' THEN ' +
'+ ' +
'''('' + ' +
'( ' +
'SELECT ' +
'QUOTENAME(c.name) ' +
'FROM sys.index_columns AS ic ' +
'JOIN sys.columns AS c ON ' +
'c.object_id = ic.object_id ' +
'AND c.column_id = ic.column_id ' +
'WHERE ' +
'ic.object_id = i.object_id ' +
'AND ic.index_id = i.index_id ' +
'AND ic.partition_ordinal = 1 ' +
') + ' +
''')'' ' +
'ELSE '''' ' +
'END ' +
'FROM sys.data_spaces AS d ' +
'WHERE ' +
'd.data_space_id = i.data_space_id ' +
') AS ds (data_space) ' +
'WHERE ' +
'i.object_id = @object_id ' +
'AND i.is_unique = 1 ' +
--filtered and hypothetical indexes cannot be candidate keys
CASE @version
WHEN '' THEN 'AND i.has_filter = 0 '
ELSE ''
END +
'AND i.is_hypothetical = 0 ' +
'AND i.is_disabled = 0 ' +
'ORDER BY ' +
'i.index_id ' EXEC sp_executesql
@sql,
N'@object_id INT, @crlf CHAR(2)',
@object_id, @crlf SELECT
'ALTER TABLE ' +
QUOTENAME(OBJECT_SCHEMA_NAME(fk.parent_object_id)) + '.' +
QUOTENAME(OBJECT_NAME(fk.parent_object_id)) + @crlf +
CASE fk.is_not_trusted
WHEN 0 THEN 'WITH CHECK '
ELSE 'WITH NOCHECK '
END +
'ADD ' +
CASE fk.is_system_named
WHEN 0 THEN 'CONSTRAINT ' + QUOTENAME(name) + @crlf
ELSE ''
END +
'FOREIGN KEY ' + @crlf +
'( ' + @crlf +
STUFF
(
(
SELECT
(
SELECT
',' + @crlf + ' ' + QUOTENAME(c.name) AS [text()]
FROM sys.foreign_key_columns AS fc
JOIN sys.columns AS c ON
c.object_id = fc.parent_object_id
AND c.column_id = fc.parent_column_id
WHERE
fc.constraint_object_id = fk.object_id
ORDER BY
fc.constraint_column_id
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
),
1,
3,
''
) + @crlf +
') ' +
'REFERENCES ' +
QUOTENAME(OBJECT_SCHEMA_NAME(fk.referenced_object_id)) + '.' +
QUOTENAME(OBJECT_NAME(fk.referenced_object_id)) + @crlf +
'( ' + @crlf +
STUFF
(
(
SELECT
(
SELECT
',' + @crlf + ' ' + QUOTENAME(c.name) AS [text()]
FROM sys.foreign_key_columns AS fc
JOIN sys.columns AS c ON
c.object_id = fc.referenced_object_id
AND c.column_id = fc.referenced_column_id
WHERE
fc.constraint_object_id = fk.object_id
ORDER BY
fc.constraint_column_id
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
),
1,
3,
''
) + @crlf +
');' +
@crlf + @crlf COLLATE database_default AS [-- Create Referencing FKs]
FROM sys.foreign_keys AS fk
WHERE
referenced_object_id = @object_id
AND is_disabled = 0
ORDER BY
key_index_id END

Step 4: Create a Stored Procedure to Script Drop Indexes and Relationships

Now you also need to create the drop scripts, this is the other half of Adam Machanic’s script.

CREATE PROC [dbo].[ScriptDropTableKeys]
@table_name SYSNAME
AS
BEGIN
SET NOCOUNT ON --Note: Disabled keys and constraints are ignored
--TODO: Drop and re-create referencing XML indexes, FTS catalogs DECLARE @crlf CHAR(2)
SET @crlf = CHAR(13) + CHAR(10)
DECLARE @version CHAR(4)
SET @version = SUBSTRING(@@VERSION, LEN('Microsoft SQL Server') + 2, 4)
DECLARE @object_id INT
SET @object_id = OBJECT_ID(@table_name)
DECLARE @sql NVARCHAR(MAX) IF @version NOT IN ('', '')
BEGIN
RAISERROR('This script only supports SQL Server 2005 and 2008', 16, 1)
RETURN
END SELECT
'ALTER TABLE ' +
QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' +
QUOTENAME(OBJECT_NAME(parent_object_id)) + @crlf +
'DROP CONSTRAINT ' + QUOTENAME(name) + ';' +
@crlf + @crlf COLLATE database_default AS [-- Drop Referencing FKs]
FROM sys.foreign_keys
WHERE
referenced_object_id = @object_id
AND is_disabled = 0
ORDER BY
key_index_id DESC SET @sql = '' +
'SELECT ' +
'statement AS [-- Drop Candidate Keys] ' +
'FROM ' +
'( ' +
'SELECT ' +
'CASE ' +
'WHEN 1 IN (i.is_unique_constraint, i.is_primary_key) THEN ' +
'''ALTER TABLE '' + ' +
'QUOTENAME(OBJECT_SCHEMA_NAME(i.object_id)) + ''.'' + ' +
'QUOTENAME(OBJECT_NAME(i.object_id)) + @crlf + ' +
'''DROP CONSTRAINT '' + QUOTENAME(i.name) + '';'' + ' +
'@crlf + @crlf COLLATE database_default ' +
'ELSE ' +
'''DROP INDEX '' + QUOTENAME(i.name) + @crlf + ' +
'''ON '' + ' +
'QUOTENAME(OBJECT_SCHEMA_NAME(object_id)) + ''.'' + ' +
'QUOTENAME(OBJECT_NAME(object_id)) + '';'' + ' +
'@crlf + @crlf COLLATE database_default ' +
'END AS statement, ' +
'i.index_id ' +
'FROM sys.indexes AS i ' +
'WHERE ' +
'i.object_id = @object_id ' +
'AND i.is_unique = 1 ' +
--filtered and hypothetical indexes cannot be candidate keys
CASE @version
WHEN '' THEN 'AND i.has_filter = 0 '
ELSE ''
END +
'AND i.is_hypothetical = 0 ' +
'AND i.is_disabled = 0 ' +
') AS x ' +
'ORDER BY ' +
'index_id DESC ' EXEC sp_executesql
@sql,
N'@object_id INT, @crlf CHAR(2)',
@object_id, @crlf END

Step 5: Bringing them all together

Now you have the two Stored Procedures, all you have to do is to loop though all the tables in your database and pass that as the parameter of the Stored Procedure. First we use ScriptCreateTableKeys.

DECLARE @TableName nvarchar(255)
DECLARE MyTableCursor Cursor
FOR
SELECT name FROM sys.tables WHERE [type] = 'U' and name <> 'sysdiagrams' ORDER BY name
OPEN MyTableCursor FETCH NEXT FROM MyTableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ScriptCreateTableKeys @TableName FETCH NEXT FROM MyTableCursor INTO @TableName
END
CLOSE MyTableCursor
DEALLOCATE MyTableCursor

Then let us use ScriptDropTableKeys:

DECLARE @TableName nvarchar(255)
DECLARE MyTableCursor Cursor
FOR
SELECT name FROM sys.tables WHERE [type] = 'U' and name <> 'sysdiagrams' ORDER BY name
OPEN MyTableCursor FETCH NEXT FROM MyTableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ScriptDropTableKeys @TableName FETCH NEXT FROM MyTableCursor INTO @TableName
END
CLOSE MyTableCursor
DEALLOCATE MyTableCursor

Just make sure when you execute them, output the results as text so you can easily copy and paste the results. Save the first results as “CreateKeysAndIndexes.sql” and the second as “DropKeysAndIndexes.sql

Step 6: Run your saved scripts

In this order, run your scripts and wait for the results, time wait might vary depending on your database size.

  1. DropKeysAndIndexes.sql
  2. ChangeCollation.sql
  3. CreateKeysAndIndexes.sql

Easy way to change collation of all database objects in SQL Server的更多相关文章

  1. Azure SQL Database (20) 使用SQL Server 2016 Upgrade Advisor

    <Windows Azure Platform 系列文章目录>  Azure SQL Database (19) Stretch Database 概览      Azure SQL Da ...

  2. [转]SQL SERVER – Importance of Database Schemas in SQL Server

    原文地址http://blog.sqlauthority.com/2009/09/07/sql-server-importance-of-database-schemas-in-sql-server/ ...

  3. Importing/Indexing database (MySQL or SQL Server) in Solr using Data Import Handler--转载

    原文地址:https://gist.github.com/maxivak/3e3ee1fca32f3949f052 Install Solr download and install Solr fro ...

  4. python Database Poll for SQL SERVER

    python连接SQL SERVER数据库: Python编程中可以使用SQL SERVER 进行数据库的连接及诸如查询/插入/更新等操作,但是每次连接SQL SERVER 数据库请求时,都是独立的去 ...

  5. SQLServer -- SQL Server Database Error: 内部 SQL Server 错误

    报表在SQLserver2008运行统计正常,但是在SQLserver2000运行报错,SQL直接执行报:内部 SQL Server 错误. 不断的排查,最终得到的结论是:SQLserver2000似 ...

  6. P6 Professional Installation and Configuration Guide (Microsoft SQL Server Database) 16 R1

    P6 Professional Installation and Configuration Guide (Microsoft SQL Server Database) 16 R1       May ...

  7. SQL Server Collation解惑

    某些产品会有固定的DB Collation,如果提前创建DB的时候没有按照要求指定对应的Collation,这个时候就会报错,提示你Collation不匹配.在安装SQL Server的时候有时候需要 ...

  8. SQL Server Database Backup and Restore in C#

    SQL Server Database Backup and Restore in C# Syed Noman Ali Shah,                          7 Feb 201 ...

  9. 使用 Oracle GoldenGate 在 Microsoft SQL Server 和 Oracle Database 之间复制事务

    使用 Oracle GoldenGate 在 Microsoft SQL Server 和 Oracle Database 之间复制事务 作者:Nikolay Manchev 分步构建一个跨这些平台的 ...

随机推荐

  1. Hibernate中inverse="true"的理解

    Hibernate中inverse="true"的理解 举例如下 转自:http://lijiejava.iteye.com/blog/776587 Customer类: publ ...

  2. C++自带栈与队列_stack_queue_C++

    栈和队列我们可以用C++里自带的函数使用,就不必手写了 1.栈,需要开头文件 #include<stack>  定义一个栈s:stack<int> s; 具体操作: s.emp ...

  3. vue elementui 递归 sidebar可伸缩侧边栏

    最近在学习vue 做了一个可伸缩的 侧边栏 记录下 在很多管理系统都用到 管理系统一般都长的差不多 首先是收起时候 展开时候 首先是新建一个Layout.vue <template> &l ...

  4. C# WeakReference(弱引用)

    WeakReference(弱引用)我们平常用的都是对象的强引用,如果有强引用存在,GC是不会回收对象的.我们能不能同时保持对对象的引用,而又可以让GC需要的时候回收这个对象呢?.NET中提供了Wea ...

  5. YYH的积木(NOIP模拟赛Round 6)

    题目描述 YYH手上有n盒积木,每个积木有个重量.现在他想从每盒积木中拿一块积木,放在一起,这一堆积木的重量为每块积木的重量和.现在他想知道重量最少的k种取法的重量分别是多少. 输入输出格式 输入格式 ...

  6. OS X升级到10.10之后使用pod出现问题的解决方法

     http://blog.csdn.net/dqjyong/article/details/37958067 OS X升级到10.10之后使用pod出现问题的解决方法 分类: IOS2014-07-1 ...

  7. Java设计模式_创建型模式_单例模式

    单例模式的实现: 定义一个类,在类中定义该类的静态变量,再定一个一个获取该类的静态变量的方法. UML图:

  8. Vue全局异常捕获

    之前没注意过这么个小技巧 , 可能在Vue文档里也有  暂时先记下了 方便摘要 Vue全局配置 errorHandler可以进行全局错误收集,我们可以根据这个特性对前端异常做这样的处理:业务错误直接写 ...

  9. 腾讯云通信WebIM事件回调的坑~

    最近在开过工作中用到了腾讯IM的功能,由于业务的需要主要使用到了: 1.loginInfo 用户登录,用户信息 2.getRecentContactList 获得最近联系人 3.getLastGrou ...

  10. (10)C#静态方法,静态字段,静态类,匿名类

    6.静态方法 使用静态方法就可不必用类的实例化调用次函数 class Test { public static void method() { ........ } //当调用一个method()时就 ...