Click here to Skip to main content
15,891,136 members
Articles / Database Development / SQL Server
Article

SQL Server 2000 Collation Changer

Rate me:
Please Sign up or sign in to vote.
4.88/5 (99 votes)
3 Mar 2008CPOL4 min read 638.1K   10.1K   101   196
Change collation order for all text columns in a database

Introduction

Do you have an SQL application that you need to deploy in another country? Do you need to change the collation of your SQL database and all objects in it? If the answer is yes, then this could be a very slow process to do manually. If you run the alter database script as below:

SQL
ALTER DATABASE [My_Database] COLLATE My_Collation

You will find that the database default collation is changed for new columns, but all existing columns will retain the original collation order. Changing the collation on each column is a non-trivial task, as you need to drop all indexes, full text indexes and constraints associated with the column, along with any user-defined functions. Once the collation order has been changed, you can recreate the indexes, constraints and functions. This C# tool simplifies the process by creating an SQL script that does everything for you.

Using the Code

Simply run the program, select your SQL Server database and a new collation order. You have two options: you can either simply get the program to create an SQL script that you can run later (press the "Script Only" button) or you can actually make the changes (press the "Script and Execute" button). Things to note:

  • Always back up your database before running this tool. I cannot guarantee that you will not lose data. A number of the statements cannot be run in a transaction, so there is no way of detecting a failure and rolling back.
  • On SQL Server 2000, nText columns will be recreated so your column order will be slightly different.
  • To run the script, the program sets the database into single user mode to run the ALTER DATABASE [db_name] COLLATE [Collation Name] statement. You should therefore ensure that there are no open connections on the database before running the script (use the stored procedure SP_WHO to identify any open connections).
  • Since the script will drop and then rebuild all indexes and foreign keys in the database, you will find that it could take a long time to complete (possibly hours).
  • All columns will be changed to the new collation order, even if they have a non-default collation before running the script.
  • SQL 2005 support is gradually being added. If you encounter issues or missing functionality, please let me know.
  • If you change from a case-insensitive to a case-sensitive collation order, you may find errors occurring when recreating check constraints and functions. This is because your scripts will be parsed in a case-sensitive manner once the collation order has been changed. To work around this, I would recommend running the script in the program and reviewing the output once the script has run to completion. The error messages relating to each failure will be displayed in red under the code that failed.

Change History

18 January 2006

  • Original posting.

7 March 2006

  • Fixed bug where scripting failed on databases with case-sensitive collation orders. Script no longer drops foreign key constraints unless necessary.

30 August 2006

  • Fixed bug when scripting objects owned by different owners than the owner executing the script are used. May be seen as an error when scripting to #spindtab_____.
  • Fixed bug where scripting did not recreate permissions on table functions after they were recreated.

20 March 2007

  • Triggers now disabled while changes are made.
  • Altered sequence of execution to prevent errors following user feedback.
  • Added some SQL 2005 support. Let me know if you encounter any issues.
  • Resolved issue when recreating a table function where the body of a table function is greater than 4000 characters.
  • Reinstated the functionality to only delete the required indexes and primary keys.

10 October 2007

  • Added support for changing collation where full text indexes exist, including changing language used in the full text search.
  • Fixed issue when insteadof triggers exist on views.
  • Fixed issue where nText columns end up allowing nulls when they were originally declared NOT NULL.
  • SQL 2005 allows collation order of nText columns to be modified. The script has been modified to reflect this new functionality.
  • Fixed issues encountered when user-defined data types are used.
  • Added additional SQL 2005 support, including refactoring scripting logic to allow various parts of the script to be customised for different versions of SQL server. If you need to debug or customise the scripts, it should be a little easier to understand.
  • Converted from VB.NET to C#, as I use C# at work all the time and it is more familiar to me.
  • Moved execution task to a worker thread to give a more responsive UI.
  • Fixed issues when system databases have case-sensitive sort order.

1 March 2008

  • Created new code for handling indexes, statistics and relationships in SQL 2005. This new code uses the 2005 schema views and adds scripting support for new SQL 2005 functionality, such as included columns in non-clustered indexes.
  • Fixed issues where ANSI_NULLS setting is not correct after recreation of table functions.
  • Various minor UI bugs fixed.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer RXP Services
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Views Pin
nigel.rickerby27-Apr-06 10:50
nigel.rickerby27-Apr-06 10:50 
GeneralGreat job! Pin
vanco26-Mar-06 11:37
vanco26-Mar-06 11:37 
GeneralThank you Pin
US15623-Mar-06 9:36
US15623-Mar-06 9:36 
QuestionWhy drop int FK? Pin
MrDevIt6-Mar-06 5:26
MrDevIt6-Mar-06 5:26 
AnswerRe: Why drop int FK? Pin
Alex Baker6-Mar-06 22:26
Alex Baker6-Mar-06 22:26 
AnswerRe: Why drop int FK? Pin
Alex Baker6-Mar-06 22:29
Alex Baker6-Mar-06 22:29 
GeneralGreat post - thank you Pin
MillieMoo22-Feb-06 5:49
MillieMoo22-Feb-06 5:49 
GeneralScript.sql (warning: Large, with code!) Pin
Alontier25-Jan-06 21:38
Alontier25-Jan-06 21:38 
Needed some fixes in the Script.sql file for it to work for me.
<code>USE [{0}]

DECLARE @textptr binary(16)
DECLARE @SQLSegment nvarchar(4000)
DECLARE @C Cursor
SET nocount ON

create TABLE #SQL (id int primary key identity(1,1),SQL nText)
INSERT INTO #SQL (SQL) VALUES ('ALTER database [{0}] SET single_user')
INSERT INTO #SQL (SQL) VALUES ('USE [{0}]')

INSERT INTO #SQL (SQL)
SELECT 'ALTER TABLE ['+ object_Name(id) + '] DROP CONSTRAINT [' + object_name(constid) + ']'
FROM sysconstraints C
WHERE objectproperty(constid,'IsForeignKey')=1

/*script out dropping of check constraints */

INSERT INTO #SQL (SQL)
SELECT 'ALTER TABLE [' + Object_Name(CS.id) + '] DROP CONSTRAINT ['+object_name(CS.constid)+']'
FROM sysconstraints CS
WHERE objectproperty(CS.constid,'IsCheckCnst') = 1

/*DROP calculated columns*/

INSERT INTO #SQL (SQL)
SELECT 'ALTER TABLE ['+ object_name(id)+ '] DROP COLUMN ['+name+']'
FROM syscolumns
WHERE iscomputed=1
AND objectproperty(id,'IsMSShipped')=0
AND objectproperty(id,'IsTable')=1

--DROP TABLE Functions

INSERT INTO #SQL (SQL)
SELECT 'DROP FUNCTION ['+ name+ ']'
FROM sysobjects
WHERE objectproperty(id,'IsMSShipped')=0
AND objectproperty(id,'IsTableFunction')=1

-- script DROP of indexes

INSERT INTO #SQL (SQL)
SELECT CASE WHEN (status & 4096)<>0 or (status & 2048) <> 0 THEN
'ALTER TABLE [' + object_name(id) +'] DROP CONSTRAINT ['+name+']'
--CONSTRAINT
ELSE
--index
'DROP INDEX [' + object_name(id) +'].['+name+']'
END
FROM sysindexes
WHERE /*id = @IX_ObjID AND */indid > 0 AND indid < 255 AND (status & 64)=0
AND objectproperty(id,'ISMSSHIPPED')=0
ORDER BY object_name(id),indid

-- script the changing of the database collation
INSERT INTO #SQL (SQL) VALUES ('USE [MASTER]')
INSERT INTO #SQL (SQL) VALUES ('ALTER database [{0}] COLLATE {1}')
INSERT INTO #SQL (SQL) VALUES ('USE [{0}]')

-- script out the changing of column level collation

DECLARE @CC_TableName sysname,
@ColName sysname,
@CC_Length nvarchar(100),
@CC_TypeName sysname,
@CC_OtherText nvarchar(4000),
@CC_NullText nvarchar(100)

SET @C = CURSOR FOR

SELECT O.name AS tablename,
C.name AS colname,
CASE WHEN T.name like 'n%' THEN CAST(C.length / 2 AS nvarchar(100)) ELSE CAST(C.length AS nvarchar(100)) END AS Length,
T.name AS typename,
CASE WHEN C.isnullable=1 THEN 'NULL' ELSE 'NOT NULL' END AS Nullable
FROM sysobjects O
JOIN syscolumns C
ON O.id = C.id
JOIN systypes T
ON T.xtype = C.xtype
AND T.xusertype = C.xusertype
WHERE O.type ='U'
AND objectproperty(O.id,'IsMSShipped')=0
AND C.collationid IS NOT NULL
--AND C.collation <> CAST(DATABASEPROPERTYEX(DB_NAME(),'collation') AS sysname)

OPEN @C

FETCH NEXT FROM @C INTO @CC_TableName, @ColName, @CC_Length, @CC_TypeName,@CC_NullText
WHILE @@Fetch_Status = 0
BEGIN
IF @CC_TypeName COLLATE DATABASE_DEFAULT in ('ntext','text')
BEGIN
-- we can not use the ALTER TABLE statment to change column level collation ON text columns
--we need to do each of these AS a separate transaction dur to the risks of errors

SET @SQLSegment = '
DECLARE @InError bit
SET @InError =0
BEGIN transaction
-- add a temp column
EXEC (''ALTER TABLE ['+@CC_TableName+'] add [____temp] [' + @CC_TypeName + ']'')

-- copy data to temp column
IF @@error<>0 SET @InError =1
IF @@error = 0
EXEC (''UPDATE ['+@CC_TableName+'] SET [____temp] =[' + @ColName + ']'')

-- readd origional column
IF @@error<>0 SET @InError =1
IF @@error = 0'
-- IF default CONSTRAINT must add it

IF EXISTS ( SELECT *
FROM sysconstraints
WHERE id = object_ID(@CC_TableName)
AND col_name(id,colid) = @ColName
AND (status & 5) = 5 )

-- IF there are default constraints add a bit to do that
SET @SQLSegment = @SQLSegment +

(SELECT '

EXEC (''ALTER TABLE ['+@CC_TableName+'] DROP CONSTRAINT [' + object_name(C.constid) + ']'')
IF @@error<>0 SET @InError =1
IF @@error = 0

EXEC (''ALTER TABLE ['+@CC_TableName+'] DROP COLUMN [' + @ColName + ']'')
IF @@error<>0 SET @InError =1
IF @@error = 0

EXEC ('' ALTER TABLE ['+ object_name(C.id) + '] ADD ['+O.name+'] [' + @CC_TypeName + '] CONSTRAINT [' + object_name(C.constid) + '] DEFAULT ' + replace(T.text,'''','''''') + ' '')'
FROM sysconstraints C
JOIN syscolumns O
ON C.id = O.id
AND C.colid = O.colid
JOIN syscomments T
ON T.id = C.constid
WHERE C.id = object_id(@CC_TableName)
AND (C.status & 5) = 5
AND col_name(C.id,C.colid) = @ColName) --default CONSTRAINT

ELSE

SET @SQLSegment = @SQLSegment + '
EXEC (''ALTER TABLE ['+@CC_TableName+'] DROP COLUMN [' + @ColName + ']'')

-- DROP origional column
IF @@error<>0 SET @InError =1
IF @@error = 0

EXEC (''ALTER TABLE ['+@CC_TableName+'] add [' + @ColName+'] [' + @CC_TypeName + '] '')'

SET @SQLSegment = @SQLSegment + '
-- Copy data back to origional column
IF @@error<>0 SET @InError =1
IF @@error = 0
EXEC (''UPDATE ['+@CC_TableName+'] SET [' + @ColName + '] = [____temp] '')

-- DROP temp column
IF @@error<>0 SET @InError =1
IF @@error = 0
EXEC (''ALTER TABLE ['+@CC_TableName+'] DROP COLUMN [____temp]'')
'
IF @CC_TypeName = 'NOT NULL'

SET @SQLSegment = @SQLSegment + '
-- now SET the appropriate nullability
IF @@error<>0 SET @InError =1
IF @@error = 0
EXEC (''ALTER TABLE ['+@CC_TableName+'] ALTER column [' + @ColName+'] [' + @CC_TypeName + '] '+@CC_NullText+' '')'

SET @SQLSegment = @SQLSegment + '
IF @@error<>0 SET @InError =1
IF @@error = 0
commit transaction
ELSE
rollback transaction

'

INSERT INTO #SQL VALUES (@SQLSegment)


END
ELSE
BEGIN
-- normal columns
SET @SQLSegment = 'ALTER TABLE ['+@CC_TableName COLLATE DATABASE_DEFAULT+'] ALTER Column ['+@ColName COLLATE DATABASE_DEFAULT+ '] ['+@CC_TypeName COLLATE DATABASE_DEFAULT+']'

IF @CC_TypeName COLLATE DATABASE_DEFAULT in ('nVarchar', 'varchar','char','nchar')
SET @SQLSegment = @SQLSegment COLLATE DATABASE_DEFAULT +' ('+@CC_Length COLLATE DATABASE_DEFAULT + ')'

SET @SQLSegment = @SQLSegment COLLATE DATABASE_DEFAULT + ' COLLATE DATABASE_DEFAULT ' + @CC_NullText COLLATE DATABASE_DEFAULT + '
'
INSERT INTO #SQL VALUES (@SQLSegment)

END
FETCH NEXT FROM @C INTO @CC_TableName, @ColName, @CC_Length, @CC_TypeName,@CC_NullText
END

CLOSE @C
DEALLOCATE @C

-- script out recreation of check constraints

INSERT INTO #SQL
SELECT 'ALTER TABLE [' + Object_Name(CS.id) + '] WITH NOCHECK ADD CONSTRAINT ['+object_name(CS.constid)+'] CHECK '+SC.text + '
' + CASE WHEN objectproperty(CS.constid,'CnstIsDisabled') = 1 THEN 'ALTER TABLE [' + Object_Name(CS.id) + '] NOCHECK CONSTRAINT ['+object_name(CS.constid)+']' ELSE '' END
FROM sysconstraints CS
JOIN syscomments SC
ON SC.id = CS.constid
WHERE objectproperty(CS.constid,'IsCheckCnst') = 1

--script out recreation of calculated columns

INSERT INTO #SQL
SELECT 'ALTER TABLE ['+ object_name(C.id)+ '] ADD ['+name+'] AS '+SC.text
FROM syscolumns C
JOIN syscomments SC
ON C.id = SC.id
AND C.colid = SC.number
WHERE C.iscomputed=1
AND objectproperty(C.id,'IsMSShipped')=0
AND objectproperty(C.id,'IsTable')=1

-- script out the recreation of indexes

-- create temp TABLE
create TABLE #spindtab
(
objectname sysname COLLATE DATABASE_DEFAULT NOT NULL,
index_name sysname COLLATE DATABASE_DEFAULT NOT NULL,
stats int,
groupname sysname COLLATE DATABASE_DEFAULT NOT NULL,
index_keys nvarchar(3000) COLLATE DATABASE_DEFAULT NOT NULL, -- see @IX_keys above for length descr
OrigFillFactor tinyint
)

--generate SQL to do indexes

DECLARE @IX_indid smallint, -- the index id of an index
@IX_groupid smallint, -- the filegroup id of an index
@IX_indname sysname,
@IX_groupname sysname,
@IX_status int,
@IX_keys nvarchar(3000),
@IX_dbname sysname,
@IX_ObjID int,
@IX_ObjName sysname,
@IX_OrigFillFactor tinyint

-- Check to see the the TABLE EXISTS AND initialize @IX_ObjID.

-- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196)
DECLARE ms_crs_ind cursor local static for
SELECT object_name(id), indid, groupid, name, status, OrigFillFactor FROM sysindexes
WHERE /*id = @IX_ObjID AND */indid > 0 AND indid < 255 AND (status & 64)=0
AND objectproperty(id,'ISMSSHIPPED')=0
ORDER BY object_name(id),indid

OPEN ms_crs_ind
FETCH ms_crs_ind INTO @IX_ObjName,@IX_indid, @IX_groupid, @IX_indname, @IX_status, @IX_OrigFillFactor

-- Now check out each index, figure out its type AND keys AND
-- save the info in a temporary TABLE that we'll print out at the END.
WHILE @@fetch_status >= 0
BEGIN
-- First we'll figure out what the keys are.
DECLARE @IX_i int, @IX_thiskey nvarchar(133) -- 128+5

SELECT @IX_keys = '[' + index_col(@IX_ObjName, @IX_indid, 1)+']', @IX_i = 2
IF (indexkey_property(@IX_ObjID, @IX_indid, 1, 'isdescending') = 1)
SELECT @IX_keys = @IX_keys + ' DESC'

SELECT @IX_thiskey = '['+index_col(@IX_ObjName, @IX_indid, @IX_i)+']'
IF ((@IX_thiskey IS NOT NULL) AND (indexkey_property(@IX_ObjID, @IX_indid, @IX_i, 'isdescending') = 1))
SELECT @IX_thiskey = @IX_thiskey + ' DESC'

WHILE (@IX_thiskey IS NOT NULL )
BEGIN
SELECT @IX_keys = @IX_keys + ', ' + @IX_thiskey, @IX_i = @IX_i + 1
SELECT @IX_thiskey = '[' + index_col(@IX_ObjName, @IX_indid, @IX_i) + ']'
IF ((@IX_thiskey IS NOT NULL) AND (indexkey_property(@IX_ObjID, @IX_indid, @IX_i, 'isdescending') = 1))
SELECT @IX_thiskey = @IX_thiskey + ' DESC'
END

SELECT @IX_groupname = groupname FROM sysfilegroups WHERE groupid = @IX_groupid

-- INSERT ROW FOR INDEX
INSERT INTO #spindtab VALUES (@IX_ObjName,@IX_indname, @IX_status, @IX_groupname, @IX_keys, @IX_OrigFillFactor)

-- Next index
FETCH ms_crs_ind INTO @IX_ObjName,@IX_indid, @IX_groupid, @IX_indname, @IX_status, @IX_OrigFillFactor
END
DEALLOCATE ms_crs_ind

-- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
DECLARE @IX_empty varchar(1) SELECT @IX_empty = ''
DECLARE @IX_des1 varchar(35), -- 35 matches spt_values
@IX_des2 varchar(35),
@IX_des4 varchar(35),
@IX_des32 varchar(35),
@IX_des64 varchar(35),
@IX_des2048 varchar(35),
@IX_des4096 varchar(35),
@IX_des8388608 varchar(35),
@IX_des16777216 varchar(35)

SELECT @IX_des1 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 1 --ignoor duplicate keys

SELECT @IX_des2 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 2 --unique
SELECT @IX_des4 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 4 --ignoor duplicate rows
SELECT @IX_des32 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 32 --hypothetical
SELECT @IX_des64 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 64 --statistics
SELECT @IX_des2048 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 2048 --primary key
SELECT @IX_des4096 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 4096 --unique key
SELECT @IX_des8388608 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 8388608 --auto create
SELECT @IX_des16777216 = name FROM master.dbo.spt_values WHERE type = 'I' AND number = 16777216 --stats no recompute

-- DISPLAY THE RESULTS


INSERT INTO #SQL
SELECT CASE WHEN (stats & 4096)<>0 or (stats & 2048) <> 0 THEN
--CONSTRAINT
'ALTER TABLE ['+objectname+'] ADD CONSTRAINT ['+index_name+'] '
+ CASE WHEN (stats & 2048)<>0 THEN 'PRIMARY KEY ' ELSE 'UNIQUE ' END
+ CASE WHEN (stats & 16)<>0 THEN 'clustered' ELSE 'nonclustered' END
+ ' ('+index_keys+')'
+ CASE WHEN OrigFillFactor >0 THEN ' WITH FILLFACTOR =' + CAST(OrigFillFactor AS nvarchar(3)) ELSE @IX_empty END
+ ' ON ['+groupname+']
' COLLATE DATABASE_DEFAULT

ELSE
-- index

'CREATE ' + CASE WHEN (stats & 2)<>0 THEN @IX_des2 +' ' ELSE @IX_empty END +CASE WHEN (stats & 16)<>0 THEN 'clustered' ELSE 'nonclustered' END +' INDEX'
+ ' ['+ index_name +'] ON ['+objectname+'] ('+index_keys+')'
+ CASE WHEN OrigFillFactor >0 or (stats & 1) <> 0 or (stats & 16777216) <> 0 THEN ' WITH ' ELSE @IX_empty END
+ CASE WHEN OrigFillFactor >0 THEN 'PAD_INDEX, FILLFACTOR = ' +CAST(OrigFillFactor AS nvarchar(3) ) ELSE @IX_empty END
+ CASE WHEN (stats & 1) <> 0 THEN ', '+ @IX_des1 ELSE @IX_empty END
+ CASE WHEN (stats & 16777216) <> 0 THEN ', '+ @IX_des16777216 ELSE @IX_empty END
+ ' ON ['+groupname+']
'
END
FROM #spindtab

DROP TABLE #spindtab

-- script recreation of foiegn keys

-- script out foreign keys
DECLARE @FK_KeyName sysname,
@FK_TableName sysname,
@FK_ReferencedTable sysname,
@constid int,
@Col1 sysname,
@Col2 sysname,
@ColList1 nvarchar(2000),
@ColList2 nvarchar(2000),
@CnstIsUpdateCascade bit,
@CnstIsNotRepl bit,
@CnstIsDeleteCascade bit,
@CnstIsDisabled bit,
@C2 cursor

SET @C = CURSOR FOR

SELECT object_Name(id) AS TableName,
object_name(constid) AS KeyName,
(SELECT distinct object_name(rkeyid) FROM sysforeignkeys FK WHERE FK.constid = C.constid) AS ReferencedTable,
constid,
objectproperty(constid,'CnstIsUpdateCascade') CnstIsUpdateCascade,
objectproperty(constid,'CnstIsDeleteCascade') CnstIsDeleteCascade,
objectproperty(constid,'CnstIsNotRepl') CnstIsNotRepl,
objectproperty(constid,'CnstIsDisabled') CnstIsDisabled
FROM sysconstraints C
WHERE objectproperty(constid,'IsForeignKey')=1

OPEN @C

FETCH NEXT FROM @C INTO @FK_TableName, @FK_KeyName, @FK_ReferencedTable,@constid, @CnstIsUpdateCascade, @CnstIsDeleteCascade, @CnstIsNotRepl,@CnstIsDisabled
WHILE @@fetch_Status =0
BEGIN
SET @ColList1 = ''
SET @ColList2 = ''

SET @C2 = CURSOR FOR
SELECT FC.name,
RC.name

FROM sysforeignkeys FK
JOIN syscolumns FC
ON FC.colid = FK.fkey
AND FC.id = FK.fkeyid
JOIN syscolumns RC
ON RC.colid = FK.rkey
AND RC.id = FK.rkeyid
WHERE FK.constid = @constid

OPEN @C2
FETCH NEXT FROM @C2 INTO @Col1, @Col2
WHILE @@Fetch_status=0
BEGIN
IF len(@ColList1) > 0
SET @ColList1 = @ColList1 COLLATE DATABASE_DEFAULT+', '
IF len(@ColList2) > 0
SET @ColList2 = @ColList2 COLLATE DATABASE_DEFAULT+', '

SET @ColList1 = @ColList1 COLLATE DATABASE_DEFAULT +'[' + @Col1 COLLATE DATABASE_DEFAULT + ']'
SET @ColList2 = @ColList2 COLLATE DATABASE_DEFAULT +'[' + @Col2 COLLATE DATABASE_DEFAULT + ']'

FETCH NEXT FROM @C2 INTO @Col1, @Col2
END
CLOSE @C2
DEALLOCATE @C2

SET @SQLSegment = 'ALTER TABLE ['+ @FK_TableName COLLATE DATABASE_DEFAULT + '] WITH NOCHECK ADD CONSTRAINT [' + @FK_KeyName COLLATE DATABASE_DEFAULT + '] FOREIGN KEY ('+@ColList1 COLLATE DATABASE_DEFAULT + ') REFERENCES [' + @FK_ReferencedTable COLLATE DATABASE_DEFAULT+'] ('+ @ColList2 COLLATE DATABASE_DEFAULT +')'
IF @CnstIsUpdateCascade =1
SET @SQLSegment =@SQLSegment + ' ON UPDATE CASCADE'

IF @CnstIsDeleteCascade =1
SET @SQLSegment =@SQLSegment + ' ON DELETE CASCADE'

IF @CnstIsNotRepl =1
SET @SQLSegment =@SQLSegment + ' NOT FOR REPLICATION'
SET @SQLSegment = @SQLSegment +'
'

INSERT INTO #SQL VALUES (@SQLSegment)

IF @CnstIsDisabled=1
BEGIN
SET @SQLSegment = 'ALTER TABLE ['+ @FK_TableName + '] NOCHECK CONSTRAINT [' + @FK_KeyName + ']
'
INSERT INTO #SQL VALUES (@SQLSegment)
END

FETCH NEXT FROM @C INTO @FK_TableName, @FK_KeyName, @FK_ReferencedTable,@constid, @CnstIsUpdateCascade, @CnstIsDeleteCascade, @CnstIsNotRepl,@CnstIsDisabled
END

CLOSE @C
DEALLOCATE @C

-- Script out the creation of the TABLE functions last!

--first switch to use the correct database
INSERT INTO #SQL (SQL) VALUES ('')

--get a text pointer
SELECT @textptr = TEXTPTR(SQL) FROM #SQL WHERE id = (SELECT MAX(id) FROM #SQL)

SET @SQLSegment = '
USE [{0}]
'

UPDATETEXT #SQL.SQL @textptr NULL 0 @SQLSegment

DECLARE @FunctionName sysname,
@LastFunctionName sysname

SET @LastFunctionName =''

SET @C = CURSOR FOR
SELECT name AS functionName,
SC.text
FROM sysobjects O
JOIN syscomments SC
ON O.id = SC.id
WHERE objectproperty(O.id,'IsTableFunction') =1
ORDER BY O.name,
SC.colid

OPEN @C
FETCH NEXT FROM @C INTO @FunctionName, @SQLSegment
WHILE @@Fetch_Status=0
BEGIN
IF @FunctionName<>@LastFunctionName
BEGIN
INSERT INTO #SQL (SQL) VALUES ('')

--get a text pointer
SELECT @textptr = TEXTPTR(SQL) FROM #SQL WHERE id = (SELECT MAX(id) FROM #SQL)

SET @LastFunctionName =@FunctionName

END

UPDATETEXT #SQL.SQL @textptr NULL 0 @SQLSegment

FETCH NEXT FROM @C INTO @FunctionName, @SQLSegment
END
CLOSE @C
DEALLOCATE @C

-- finally SET back to multi user access
INSERT INTO #SQL VALUES ('ALTER database [{0}] SET multi_user')

SELECT * FROM #SQL ORDER BY id

RETURN</code>
GeneralRe: Script.sql (warning: Large, with code!) Pin
Alex Baker25-Jan-06 21:45
Alex Baker25-Jan-06 21:45 
GeneralRe: Script.sql (warning: Large, with code!) Pin
Alontier25-Jan-06 23:05
Alontier25-Jan-06 23:05 
GeneralRe: Script.sql (warning: Large, with code!) Pin
Alex Baker25-Jan-06 23:19
Alex Baker25-Jan-06 23:19 
GeneralRe: Script.sql (warning: Large, with code!) Pin
Craig Knighton26-Jul-06 6:26
Craig Knighton26-Jul-06 6:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.