SQL Server: Only Database and Object Collation Change
Well this gonna be a boring and very lengthy blog. But I have prepared it after researching with the geeks' docs. I finally made my database with another collation. Previously I thoght that only unique and primary key will need to be recreated but the thing is nonclustered and non unique index also need to be changed. Any way go through my steps and suggests if I missed any thing. At the end I have given all the sources I used.
Sources:
http://sqlsolace.blogspot.com.au/2010/08/automatically-script-non-clustered.html
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Summary:
The existing Database connection
can be changed using the ALTER Database command provided in SQL Server. To
change the collation settings
- Restrict the Database access to Single
User Mode
- Change the Database collation using the
following syntax.
ALTER DATABASE dbname COLLATE [Replace Actual Collation]
GO
This will only change the
collation of the Database and not the collation of the Database objects
(Tables) if any exists already. We need to explicitly change the collation of
the character (VARCHAR / NVARCHAR) columns for each table. To change the
collation settings for columns
- Take the backup of all the Indexes and
constraints of the tables with Character columns in the Database
- Drop all the Indexes and constraints (Primary
Key, Foreign Key, Defaults etc)
- Change the
Collation setting for the table columns. The below script can be used to
generate the script that identifies the character columns and replace it
with the new collation in the Database
Command
Set:
- USE GUI to take the DB in SINGLE
USER Mode
- Change the DB Collation and Check.
ALTER DATABASE COLLATION_TEST
COLLATE Latin1_General_CI_AS
Go
SELECT SERVERPROPERTY('Collation') AS 'Collation'
GO
Output:
Latin1_General_CI_AS
- Script for change collation of
all columns and name it ChangeCollation.sql
SELECT 'ALTER TABLE [' + SYSOBJECTS.Name + '] ALTER COLUMN [' + SYSCOLUMNS.Name + '] ' +
SYSTYPES.name +
CASE systypes.NAME
WHEN 'text'
THEN ' '
ELSE
'(' + RTRIM(CASE SYSCOLUMNS.length
WHEN -1 THEN 'MAX'
ELSE CONVERT(CHAR,SYSCOLUMNS.length)
END) + ') '
END
+ ' ' + ' COLLATE
Latin1_General_CI_AS ' + CASE ISNULLABLE WHEN
0 THEN 'NOT NULL'
ELSE 'NULL' END
FROM SYSCOLUMNS
, SYSOBJECTS , SYSTYPES
WHERE SYSCOLUMNS.ID = SYSOBJECTS.ID
AND SYSOBJECTS.TYPE = 'U'
AND SYSTYPES.Xtype = SYSCOLUMNS.xtype
AND SYSCOLUMNS.COLLATION IS NOT NULL
AND NOT ( sysobjects.NAME LIKE 'sys%' )
AND NOT ( SYSTYPES.name LIKE 'sys%' )
GO
- Script to make all Index and Keys and execute the procedure like [do this in a text pad. Collect the table list from above script. Eliminate duplicate and run below SP.]
exec
ScriptCreateTableKeys
Table1
exec
ScriptCreateTableKeys
Table2
….
- Save the output of all the above query as CreateKeysAndIndexes.sql
/*
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 ('2005', '2008')
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 '2005' 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 '2008' 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
- Drop index and key script needs to be
made by running below query and save it as DropKeysAndIndexes.sql
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 ('2005', '2008')
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 '2008' 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
- Create a procedure usp_GenerateIndexesScript to generate create script of all non-clustered index.
----- A: First Enable OLE Automation -------sp_configure 'show advanced options', 1;GORECONFIGURE;GOsp_configure 'Ole Automation Procedures', 1;GORECONFIGURE;GOsp_configure 'Agent XPs', 1;GORECONFIGURE;GOsp_configure 'show advanced options', 1;GORECONFIGURE;GO
----- B: Second Create the Proc usp_OLEwritefile. This SP actually write file --- from SQL -–
CREATE PROCEDURE [dbo].[usp_OLEWriteFile] (@FileName varchar(1000), @TextData NVARCHAR(MAX),@FileAction VARCHAR(12)) AS
BEGINDECLARE @OLEfilesytemobject INTDECLARE @OLEResult INTDECLARE @FileID INTEXECUTE @OLEResult =sp_OACreate 'Scripting.FileSystemObject', @OLEfilesytemobject OUTIF @OLEResult <> 0PRINT 'Error: Scripting.FileSystemObject'
-- check if file existsEXEC sp_OAMethod @OLEfilesytemobject, 'FileExists', @OLEresult OUT, @FileName
-- if file esistsIF (@OLEresult=1 AND @FileAction = 'APPEND') OR (@OLEresult=0)
BEGINIF (@FileAction = 'CREATENEW')PRINT 'New file specified, creating...'IF (@OLEresult=1 AND @FileAction = 'APPEND')PRINT 'File exists, appending...'
IF (@OLEresult=0 AND @FileAction = 'APPEND')PRINT 'File doesnt exist, creating...'-- open fileEXECUTE @OLEResult = sp_OAMethod @OLEfilesytemobject, 'OpenTextFile', @FileID OUT,
@FileName, 8, 1
IF @OLEResult <>0 PRINT 'Error: OpenTextFile'
-- write Text1 to the fileEXECUTE @OLEResult = sp_OAMethod @FileID, 'WriteLine', Null, @TextData
IF @OLEResult <> 0
PRINT 'Error : WriteLine'
ELSE
PRINT 'Success'
END
IF (@OLEresult=1 AND @FileAction = 'CREATENEW')
PRINT 'File Exists, specify APPEND if this is the desired action'EXECUTE @OLEResult = sp_OADestroy @FileIDEXECUTE @OLEResult = sp_OADestroy @OLEfilesytemobjectENDGO
----- C: Then Create the Proc usp_GenerateIndexesScript -----
USE [COLLATION_TEST]GO/****** Object: StoredProcedure [dbo].[usp_GenerateIndexesScript] Script Date: 08/01/2012 12:44:53 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[usp_GenerateIndexesScript](@IncludeFileGroup bit = 1,@IncludeDrop bit = 1,@destinationparameter NVARCHAR(1000) = NULL)ASBEGIN-- Get all existing indexes, but NOT the primary keysDECLARE Indexes_cursor CURSORFOR SELECTSC.Name AS SchemaName, SO.Name AS TableName, SI.Object_Id AS TableId, SI.[Name] AS IndexName, SI.Index_ID AS IndexId, FG.[Name] AS FileGroupName, CASE WHEN SI.Fill_Factor = 0 THEN 100 ELSE SI.Fill_Factor END Fill_FactorFROM sys.indexes SILEFT JOIN sys.filegroups FGON SI.data_space_id = FG.data_space_idINNER JOIN sys.objects SOON SI.object_id = SO.object_idINNER JOIN sys.schemas SCON SC.schema_id = SO.schema_idWHERE ObjectProperty(SI.Object_Id, 'IsUserTable') = 1AND SI.[Name] IS NOT NULL
AND SI.is_primary_key = 0
AND SI.is_unique_constraint = 0
AND IndexProperty(SI.Object_Id, SI.[Name], 'IsStatistics') = 0
AND FG.[Name] IS NOT NULL
ORDER BY SC.Name , SO.Name ,SI.[Name]
DECLARE @SchemaName sysname
DECLARE @TableName sysnameDECLARE @TableId intDECLARE @IndexName sysnameDECLARE @FileGroupName sysnameDECLARE @IndexId intDECLARE @FillFactor intDECLARE @NewLine nvarchar(4000)SET @NewLine = CHAR(13) + CHAR(10)DECLARE @Tab nvarchar(4000)SET @Tab = Space(4)DECLARE @SQLOutput nvarchar(max)
SET @SQLOutput = ''
-- Loop through all indexesOPEN Indexes_cursor
FETCH NEXTFROM Indexes_cursorINTO @SchemaName, @TableName, @TableId, @IndexName, @IndexId, @FileGroupName, @FillFactorWHILE (@@Fetch_Status = 0)BEGINDECLARE @sIndexDesc nvarchar(4000)DECLARE @sCreateSql nvarchar(4000)DECLARE @sDropSql nvarchar(4000)SET @sIndexDesc = '-- Index ' + @IndexName + ' on table ' + @SchemaName + '.' + @TableNameSET @sDropSql = 'IF EXISTS(SELECT 1' + @NewLine+ ' FROM sys.indexes si' + @NewLine+ ' INNER JOIN sys.objects so' + @NewLine+ ' ON so.object_id = si.object_id' + @NewLine+ ' WHERE si.[Name] = N''' + @IndexName + ''' -- Index Name' + @NewLine+ ' AND so.[Name] = N''' + @TableName + ''') -- Table Name' + @NewLine+ 'BEGIN' + @NewLine+ ' DROP INDEX [' + @IndexName + '] ON [' + @SchemaName + '].[' + @TableName + ']' + @NewLine+ 'END' + @NewLine
SET @sCreateSql = 'CREATE '-- Check if the index is uniqueIF (IndexProperty(@TableId, @IndexName, 'IsUnique') = 1)BEGINSET @sCreateSql = @sCreateSql + 'UNIQUE 'END--END IF-- Check if the index is clusteredIF (IndexProperty(@TableId, @IndexName, 'IsClustered') = 1)BEGINSET @sCreateSql = @sCreateSql + 'CLUSTERED 'END--END IFSET @sCreateSql = @sCreateSql + 'INDEX [' + @IndexName + '] ON [' + @SchemaName + '].[' + @TableName + ']' + @NewLine + '(' + @NewLine
-- Get all columns of the indexDECLARE IndexColumns_cursor CURSORFOR SELECT SC.[Name],IC.[is_included_column],IC.is_descending_keyFROM sys.index_columns ICINNER JOIN sys.columns SCON IC.Object_Id = SC.Object_IdAND IC.Column_ID = SC.Column_IDWHERE IC.Object_Id = @TableIdAND Index_ID = @IndexIdORDER BY IC.[is_included_column],IC.key_ordinalDECLARE @IxColumn sysnameDECLARE @IxIncl bitDECLARE @Desc bitDECLARE @IxIsIncl bit SET @IxIsIncl = 0DECLARE @IxFirstColumn bit SET @IxFirstColumn = 1-- Loop through all columns of the index and append them to the CREATE statement
OPEN IndexColumns_cursorFETCH NEXTFROM IndexColumns_cursorINTO @IxColumn, @IxIncl, @DescWHILE (@@Fetch_Status = 0)BEGINIF (@IxFirstColumn = 1)BEGINSET @IxFirstColumn = 0ENDELSEBEGIN--check to see if it's an included columnIF (@IxIsIncl = 0) AND (@IxIncl = 1)BEGINSET @IxIsIncl = 1SET @sCreateSql = @sCreateSql + @NewLine + ')' + @NewLine + 'INCLUDE' + @NewLine + '(' + @NewLineENDELSEBEGINSET @sCreateSql = @sCreateSql + ',' + @NewLineEND--END IFEND--END IFSET @sCreateSql = @sCreateSql + @Tab + '[' + @IxColumn + ']'-- check if ASC or DESCIF @IxIsIncl = 0BEGINIF @Desc = 1BEGINSET @sCreateSql = @sCreateSql + ' DESC'ENDELSEBEGINSET @sCreateSql = @sCreateSql + ' ASC'END--END IFEND--END IFFETCH NEXTFROM IndexColumns_cursorINTO @IxColumn, @IxIncl, @DescEND--END WHILECLOSE IndexColumns_cursorDEALLOCATE IndexColumns_cursor
SET @sCreateSql = @sCreateSql + @NewLine + ') 'IF @IncludeFileGroup = 1BEGINSET @sCreateSql = @sCreateSql + 'ON ['+ @FileGroupName + ']' + @NewLineENDELSEBEGINSET @sCreateSql = @sCreateSql + @NewLineEND--END IFPRINT '-- ************************************************'
PRINT @sIndexDesc
PRINT '-- *************************************************'
SET @SQLOutput = @SQLOutput + '-- **********************************************************************' + @NewLineSET @SQLOutput = @SQLOutput + @sIndexDesc + @NewLine
SET @SQLOutput = @SQLOutput + '-- **********************************************************************' + @NewLineSET @SQLOutput = @SQLOutput + @NewLineIF @IncludeDrop = 1BEGINPRINT @sDropSqlPRINT 'GO'SET @SQLOutput = @SQLOutput + @sDropSql + @NewLineSET @SQLOutput = @SQLOutput + 'GO' + @NewLineEND--END IFPRINT @sCreateSqlPRINT 'GO' + @NewLine + @NewLineSET @SQLOutput = @SQLOutput + @sCreateSql + @NewLineSET @SQLOutput = @SQLOutput + 'GO' + @NewLine
FETCH NEXTFROM Indexes_cursorINTO @SchemaName, @TableName, @TableId, @IndexName, @IndexId, @FileGroupName, @FillFactorEND--END WHILECLOSE Indexes_cursorDEALLOCATE Indexes_cursor
-- @SQLOutput contains the output to place in a file
IF LEN(@destinationparameter) > 0BEGINEXEC dbo.usp_OLEwritefile @FileName = @destinationparameter, @TextData = @SQLOutput, @FileAction = 'CREATENEW'END--PRINT @SQLOutputENDGO----------------- recreate all non clustered indexes ---------------
EXEC dbo.usp_GenerateIndexesScript@IncludeFileGroup = 1,@IncludeDrop = 1,@destinationparameter = 'E:\temp\Collation_Test_20120731\MyNonClusteredIndexes.sql'
- Drop Script of all Non Clustered Index [Don't Fire it Now !!!]
------------------------- Drop the Indexes --------------------------------------------------------------------------------------------------------
declare @name sysnamedeclare @TableName sysnamedeclare @sql varchar(4096)declare vCursor cursor forselect [name], [TableName] from NonClusteredIndexesToDelete order by [name]
open vCursorfetch NEXT from vCursor into @name, @TableNamewhile @@FETCH_STATUS = 0beginset @sql = 'drop index ' + @TableName + '.' + @nameexec (@sql)fetch NEXT from vCursor into @name, @TableNameEndclose vCursordeallocate vCursor
- Run command in below sequence
- DropKeysAndIndexes.sql
- Run command on step 8
- ChangeCollation.sql
- CreateKeysAndIndexes.sql
- MyNonClusteredIndexes.sql
Sources:
http://sqlsolace.blogspot.com.au/2010/08/automatically-script-non-clustered.html
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Comments
Post a Comment