SQL Server Case Sensitivity in Foreign Key
We're having issues trying to update all of our user to lowercase usernames in SQL Server. We're doing this to support recent changes in our app. Specifically the following query is failing with an FK Constraint error on another table that references [User].[Username]
Update [User]
Set [Username] = 'someuser' where [username] = 'SomeUser'
The user 'someuser' does exist in the foreign table already and the casing matches 'SomeUser'. The FK isn't set to Cascade on Update at the moment. I was going to go that route, but there are quite a few references to the [User].[Username] column and when I started going down that road it was a bit messy. Besides, I'd rather tackle the root cause - why is SQL enforcing the case match on the Key?
I'm not the best with the internals of SQL Server, but I have cheched the COLLATION using the guidance of another SO question (http://stackoverflow.com/questions/1411161/sql-server-check-case-sensitivity) and I get these results.
SELECT SERVERPROPERTY('COLLATION')
=> SQL_Latin1_General_CP1_CI_AS
SELECT DATABASEPROPERTYEX('MyDB', 'Collation') SQLCollation;
=> SQL_Latin1_General_CP1_CI_AS
select table_name, column_name, collation_name
from information_schema.columns
where table_name = 'User'
=> User Username SQL_Latin1_General_CP1_CI_AS
select table_name, column_name, collation_name
from information_schema.columns
where table_name = 'ForeignTable'
=> ForeignTable User_Username SQL_Latin1_General_CP1_CI_AS
I'm out of ideas on what to check. Hoping someone has a solution out there. I'm happy to check any settings in SQL (though you might have to guide me to where they're at in Management Studio or the Query to run to get them)开发者_运维百科 or provide any additional detail if I'm haven't given enough info.
UPDATE: Error as requested
Msg 547, Level 16, State 0, Line 4
The UPDATE statement conflicted with the REFERENCE constraint "FK_ForeignTable_User". The conflict occurred in database "MyDB", table "dbo.ForeignTable", column 'User_Username'.
The statement has been terminated.
Based on the fact that all collations align, then one reason may be a trigger firing on update. This is why the exact error message is important.
For example, do you have an audit trigger attempting to log the update into a case sensitive column?
Saying that, I've never tried to create an FK between 2 different collations (I can't test right now): not sure if it would work.
One factual way to test for SomeUser vs someuser would be a simple GROUP BY: do you get one count per value or one for both values
Edit: check for trailing spaces...
精彩评论