You cannot directly change the collation of an existing column that is defined as a Unicode data type like nchar or nvarchar. You must create a new column with the desired collation, copy the data into it, drop the old column, and rename the new one. This is because the error message indicates that the collation is not supported on those specific data types in the current context, often due to a mismatch with the database or server default collations.
What You'll Need
- SQL Server Management Studio (SSMS): The primary interface for connecting to and managing your database instance.
- Access to a Database Administrator (DBA) role: The steps below require permissions to alter existing tables and change database-level settings.
- A backup of your data: Before performing any structural changes to a production table, create a full backup or a transaction log backup to ensure data can be restored in case of an unexpected failure.
- Rights to modify the database: You must be the owner of the database or have explicit ALTER permission on the target tables.
Step-by-Step
- Diagnose the Error: Run the script that originally triggered
Error 459. Note the specific column name and the error message details. The error usually appears when trying to alter a table (e.g.,ALTER TABLE dbo.YourTable ALTER COLUMN YourColumn NVARCHAR(50)) or when trying to use a collation clause in anINSERTorSELECTstatement where the column is defined as Unicode. The specific error text is vital for identifying the mismatch. - Identify the Desired Collation: You need to know exactly which collation you want to apply. This is often determined by the database's default collation or a specific requirement for data comparison. You can view the current database default collation by running
SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation');. Common options includeSQL_Latin1_General_CP1_CI_ASorLatin1_General_100_CI_AS. - Create a New Column: Add a new column to your table with the same data type and length as the problematic column, but explicitly specify the desired collation. For example, if your existing column is
varCharName NVARCHAR(50)and you want to change it to the Latin1_General collation, run the following script:
ALTER TABLE dbo.YourTable
ADD varCharName_New NVARCHAR(50) COLLATE Latin1_General_100_CI_AS;
- Populate the New Column: Copy the data from the old column to the new one. This step ensures that the data is moved with the new collation settings applied. The simplest way to do this is using a
INSERT INTOstatement:
INSERT INTO dbo.YourTable (varCharName_New)
SELECT varCharName FROM dbo.YourTable;
This statement will implicitly convert the data from the source column's collation to the target column's collation. If there are any characters that are not supported by the target collation, this operation will fail, so run it carefully.
- Verify Data Integrity: Before proceeding, compare the data in the two columns to ensure they match. You can do this by selecting rows where the values differ or running a checksum comparison:
SELECT COUNT(*) FROM dbo.YourTable
WHERE varCharName_New <> varCharName;
Ensure this count is zero. If there is a discrepancy, the data conversion or the collation settings may be incompatible.
- Drop the Old Column: Once you have confirmed that the new column contains the correct data, you can safely remove the old column. This step is irreversible, so double-check that you are dropping the correct column:
ALTER TABLE dbo.YourTable DROP COLUMN varCharName;
- Rename the New Column: Finally, rename the new column to the original name to restore the table's original structure. This is done using the
sp_renamesystem stored procedure:
EXEC sp_rename 'dbo.YourTable.varCharName_New', 'varCharName', 'COLUMN';
- Update Database Collation (Optional): If the error occurred because the database default collation was causing issues with Unicode columns, you might consider changing the database default collation. However, this is a server-wide change that can affect all other databases on the instance and is not recommended unless absolutely necessary. To do this, you would typically need to stop the SQL Server service and use the command line or a startup parameter to specify the new collation. This is an advanced administrative task.
Common Mistakes
- Assuming Collation Can Be Changed Directly: A frequent mistake is attempting to use the
COLLATEclause directly in anALTER TABLEstatement for Unicode columns. This syntax is often rejected by the engine, resulting in the error. You must use the workaround of creating a new column. - Ignoring Data Compatibility: When selecting data into the new column, you must ensure the target collation supports the characters in your source data. For example, if your data contains Japanese characters, using a Latin-based collation like
SQL_Latin1_General_CP1_CI_ASwill cause the insert to fail, as that collation does not support those characters. - Forgetting to Drop the Old Column: After the new column is created and populated, leaving the old column in place can lead to confusion and potential data integrity issues. It is important to remove the original column to maintain a clean schema.
- Modifying the Default Database Collation: Changing the database default collation is a drastic measure. It can cause widespread issues with existing tables and objects that rely on the previous collation. This should only be considered as a last resort.
Tips
- Use a Transaction: Wrap your entire process in a transaction. This allows you to roll back the changes if anything goes wrong during the data copy or column drop steps. For example:
BEGIN TRANSACTION;
-- Perform steps 3 through 7 here
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
ELSE
ROLLBACK TRANSACTION;
COLLATE clause within the query itself, rather than changing the column structure. For example: SELECT * FROM dbo.YourTable WHERE varCharName COLLATE Latin1_General_100_CI_AS = 'test'.Troubleshooting
If the steps above do not resolve the issue, consider the following troubleshooting measures:
- Error During Data Copy: If the
INSERT INTOstatement fails with an error indicating invalid Unicode characters, the target collation is not compatible with the source data. You must choose a collation that supports the full range of characters in your data, such as a Unicode collation likeSQL_Latin1_General_CP1_CI_ASor a collation specific to the language of your data. - Foreign Key Constraint Failures: If you receive an error related to foreign keys after the column is renamed, you must drop the foreign key constraints and recreate them. The foreign key definition must be updated to reference the new column name.
- Index Creation Failures: If you are unable to create an index on the new column, it may be because the collation specified is not supported on the server version or because the index already exists on the old column. Ensure you drop any existing indexes before creating new ones.
- Permission Denied: If you receive a permission error, ensure that the user account running the script has the necessary
ALTERpermission on the table andCREATE INDEXpermission if you are creating indexes. - Transaction Rollback: If you used a transaction and need to undo the changes, simply run
ROLLBACK TRANSACTION;. This will revert the table to its original state.
Frequently Asked Questions
Can I change the collation of a column defined as nchar or nvarchar directly?
No, SQL Server does not allow you to change the collation of an existing column that is defined as a Unicode data type using the ALTER TABLE statement. You must use the workaround of creating a new column with the desired collation, copying the data, and then renaming the columns.
Why does the error occur?
The error occurs because the specific collation you are trying to apply is not supported on the Unicode data types in the current context. This is often due to a conflict between the column's collation and the database or server default collations.
What is the difference between char and nchar?
char and nchar are both fixed-length character data types. The difference is that char uses the database's default character set and collation, while nchar is specifically designed for Unicode data and uses the database's Unicode collation.
Is it safe to change the database default collation?
Changing the database default collation is not recommended unless absolutely necessary. It is a server-wide change that can affect all other databases on the instance and can cause widespread issues with existing tables and objects.
Can I use the COLLATE clause in a query to fix the issue?
Yes, you can use the COLLATE clause in a query to compare or sort data with a different collation without changing the column structure. This is a temporary solution that applies only to the specific query.