When attempting to compare two strings in SQL Server, the collations must match, otherwise you get this error. Collation tells SQL Server how to compare strings (i.e. CHAR, NCHAR, VARCHAR, NVARCHAR). The collation Latin1_General_CI_AS uses the Latin1_General character set, case insensitive, accent sensitive.
Some stuff you need to know before I give you the solution: There are three levels of collation in SQL Server:
- The server default collation: This is set during the SQL Server installation, and defines the default collation used for new databases created on the server. This is also the default collation used for the system databases, including TempDB. In other words, if you create a temp table without specifying the collation to use, it will use the server's default. You can find this by right-clicking on the server and selecting properties.
- The database default collation. This is the collation that will be used when tables are created in the database, without explicitly specifying the collation when creating the table. By default, this is the same as the Server's collation, but can be specified when creating the database. If you back up the database and restore it on another server with a different collation, it will keep its own collation, and not inherit that of the server. You can see this by right-clicking on the database and selecting properties.
- The field collation. This is the collation for a specific field, and exists for all string type fields in the database. If you change the collation of the database, it does not change the collation of all of the string fields in the database; only those fields that are subsequently created on the database. You can see this collation in the table designer, using sp_help TableName, or right-clicking on the field and selecting properties.
In order to fix your problem, you need to change the collation of one of the two fields you're trying to compare, to make them the same. Changing both to match the collation of the database will probably be your best practice:
ALTER TABLE MyMaster ALTER COLUMN MyMasterKey VARCHAR(30) COLLATE LATIN1_General_CI_AS
ALTER TABLE MyDetail ALTER COLUMN MyMasterKey VARCHAR(30) COLLATE LATIN1_General_CI_AS
Then you'll be able to define the foreign key:
ALTER TABLE MyDetail ADD CONSTRAINT FK_Master_Detail FOREIGN KEY (MyMasterKey) REFERENCES MyMaster(MyMasterKey)