patternsqlModerate
Trigger to change Database collation on creation
Viewed 0 times
triggerdatabasecollationcreationchange
Problem
I'm trying to create a Trigger, to alter collation of a database on its creation, but how can I catch the database name to use inside the trigger?
Obviously, this is not working.
USE master
GO
CREATE TRIGGER trg_DDL_ChangeCOllationDatabase
ON ALL SERVER
FOR CREATE_DATABASE
AS
declare @databasename varchar(200)
set @databasename =db_name()
ALTER DATABASE @databasename COLLATE xxxxxxxxxxxxxxxxxxx
GOObviously, this is not working.
Solution
You would need to use dynamic SQL, and the EVENTDATA() function.
Just sub in your collation for my fake one.
Now when I create a database...
I get this message (from the print):
ALTER DATABASE [DingDong] COLLATE al'z a-b-cee'z
Just note that if other databases (including tempdb) use different collations, you can run into problems comparing string data. You'd have to add COLLATE clauses to string comparisons where casing or accents matter, and even when they don't you can hit errors. Related question where I ran into a similar code problem here.
USE master
GO
CREATE TRIGGER trg_DDL_ChangeCOllationDatabase
ON ALL SERVER
FOR CREATE_DATABASE
AS
SET NOCOUNT ON;
DECLARE @databasename NVARCHAR(256) = N''
DECLARE @event_data XML;
DECLARE @sql NVARCHAR(4000) = N''
SET @event_data = EVENTDATA()
SET @databasename = @event_data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'NVARCHAR(256)')
SET @sql += 'ALTER DATABASE ' + QUOTENAME(@databasename) + ' COLLATE al''z a-b-cee''z'
PRINT @sql
EXEC sys.sp_executesql @sql
GOJust sub in your collation for my fake one.
Now when I create a database...
CREATE DATABASE DingDongI get this message (from the print):
ALTER DATABASE [DingDong] COLLATE al'z a-b-cee'z
Just note that if other databases (including tempdb) use different collations, you can run into problems comparing string data. You'd have to add COLLATE clauses to string comparisons where casing or accents matter, and even when they don't you can hit errors. Related question where I ran into a similar code problem here.
Code Snippets
USE master
GO
CREATE TRIGGER trg_DDL_ChangeCOllationDatabase
ON ALL SERVER
FOR CREATE_DATABASE
AS
SET NOCOUNT ON;
DECLARE @databasename NVARCHAR(256) = N''
DECLARE @event_data XML;
DECLARE @sql NVARCHAR(4000) = N''
SET @event_data = EVENTDATA()
SET @databasename = @event_data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'NVARCHAR(256)')
SET @sql += 'ALTER DATABASE ' + QUOTENAME(@databasename) + ' COLLATE al''z a-b-cee''z'
PRINT @sql
EXEC sys.sp_executesql @sql
GOCREATE DATABASE DingDongContext
StackExchange Database Administrators Q#174219, answer score: 11
Revisions (0)
No revisions yet.