This error (SQL Server Error 240 “Types don’t match between the anchor and dependent relationship”) occurs when a foreign key or join condition expects data of one type (e.g., INT, VARCHAR) but finds data of a different type in its target column. Without fixing it, queries will fail silently or crash your application. The simplest solution is to cast one side of the join to match the other, but deeper issues—like inconsistent column definitions—will require more work. Follow this guide to identify and resolve the mismatch without losing data.

What You'll Need

  • A SQL Server database client (SSMS, Azure Data Studio, or a server management tool like SQL CMD)
  • The table schema definitions (via Object Explorer or sp_help)
  • A backup of your database (before making structural changes)
  • Edit permissions for the schema where the join exists

Step-by-Step

  1. Identify the exact relationship. Open Object Explorer in SSMS and navigate to the schema containing both tables. Right-click the relationship between them and select Edit Relationship. Verify the Referenced Column, Column, and Delete Rule match your query. If the error occurs during a query, use EXEC sp_help on each table to see column data types. Common mismatch locations:
    • ID (INT) referencing a customer_name (VARCHAR)
    • DateTime stored as SMALLDATETIME vs. DATETIME
    • Boolean flags mixed with BIT and INT
  2. Check for implicit type conversions. Run this dynamic SQL to compare column definitions:
    SELECT
            t.name AS TableName,
            c.name AS ColumnName,
            DATA_TYPE,
            CHARACTER_MAXIMUM_LENGTH,
            IS_NULLABLE
        FROM
            sys.columns c
        JOIN
            sys.tables t ON c.object_id = t.object_id
        WHERE
            t.name IN ('ParentTable', 'ChildTable')
        ORDER BY
            t.name, c.column_id
    Look for columns with the same logical name but different SQL data types (e.g., int vs. bigint).
  3. Fix via the relationship editor. In the Edit Relationship dialog:
    1. Select the relationship and check the Referenced Column dropdown.
    2. Click Advanced... and ensure the Referenced Type matches the column definition.
    3. For casts in queries, modify the join condition to use explicit casting: SELECT * FROM ChildTable WHERE ChildTable.foreign_key_column = CAST(ParentTable.primary_key_column AS Type) Replace Type with the exact type (e.g., VARCHAR(50)).
  4. Standardize column definitions. If the mismatch persists, use these SQL scripts to align types:
    1. For numeric mismatches (e.g., INT vs. BIGINT):
      ALTER TABLE ChildTable ALTER COLUMN column_name BIGINT
    2. For string mismatches (e.g., VARCHAR(20) vs. NVARCHAR(255)):
      ALTER TABLE ParentTable ALTER COLUMN column_name NVARCHAR(20)
    3. For date/time conversions:
      ALTER TABLE ChildTable ALTER COLUMN column_name DATETIME2(7)
    Backup first! Test changes on a copy of the database.
  5. Test the fix. Run this query to verify both sides of the join:
    SELECT
            p.primary_key,
            p.column_name AS ParentValue,
            c.foreign_key,
            c.column_name AS ChildValue
        FROM
            ParentTable p
        LEFT JOIN
            ChildTable c ON CAST(p.primary_key AS VARCHAR(50)) = c.foreign_key_column
        WHERE
            p.primary_key IS NOT NULL
    Replace VARCHAR(50) with the exact cast type. If rows appear only on one side, the cast resolved the issue.

Common Mistakes

  1. Assuming implicit conversions work. SQL Server doesn’t always convert types automatically (e.g., 123 to VARCHAR fails). Always use explicit casting or alter tables to match.
  2. Overlooking NULLs. Mismatches can occur when NULLs are implicitly converted. Add ISNULL or COALESCE to queries: WHERE ChildTable.column = ISNULL(ParentTable.column, 'default')
  3. Ignoring stored procedures. If the error occurs in a stored procedure, trace execution with:
    SET SHOWPLAN_TEXT ON
    Then check if the WHERE clause uses implicit comparisons.
  4. Updating tables without testing. Altering schemas can break existing applications. Test in a staging environment first.

Tips

  1. Use data validation scripts. Before altering tables, validate data types with:
    SELECT * FROM ChildTable WHERE CAST(foreign_key_column AS Int) IS NOT NULL
    This catches hidden type mismatches.
  2. Audit relationships with DBCC. Run DBCC CHECKRELATION to detect broken foreign key constraints that might mask type issues.
  3. Document casting requirements. Add comments to queries explaining cast types: -- Casts ID (INT) to VARCHAR(10) for compatibility WHERE customer_id = CAST(id_column AS VARCHAR(10))
  4. Consider normalization. If repeated mismatches exist, restructure tables to eliminate joins entirely (e.g., move common data to a shared table).

Troubleshooting

  1. The error persists after casting. Check for schema differences between versions. Use:
    SELECT * FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = 'YourSchema' AND TABLE_NAME = 'ParentTable'
    to compare column definitions across deployments.
  2. Performance degrades after fixing. Aim for minimal casting. If possible, redesign the join to use a computed column:
    CREATE COMPUTED COLUMN c_id AS CAST(id AS VARCHAR(10))
        ON ParentTable
  3. Data integrity issues appear after altering. Run DBCC CHECKDB and verify referential integrity:
    EXEC sp_depends @object_name = 'ParentTable'
  4. Third-party tools report mismatches but queries work. Query-specific logic might override schema rules. Install the tool in a test environment and compare its findings with your data model.

Frequently Asked Questions

Why does SQL Server keep throwing Error 240 when I cast the value?

Error 240 occurs when the cast doesn’t resolve the fundamental type mismatch, often because the underlying column definitions still differ. Check the DATA_TYPE in INFORMATION_SCHEMA.COLUMNS and ensure the cast type matches exactly (e.g., VARCHAR(50), not just VARCHAR).

How do I find which column causes the mismatch in a complex join?

Use a query trace or profiler to capture the exact query causing the error, then inspect each column’s data type. For large tables, filter with WHERE /*!40000 JOIN_FILTER */ in SQL Server 2012+ to isolate problematic joins.

Can I fix this with a view instead of altering tables?

Yes, create a view with explicit casts: CREATE VIEW v_joined AS SELECT p.*, c.foreign_key_column AS fk FROM ParentTable p JOIN ChildTable c ON CAST(p.id AS NVARCHAR(10)) = c.id Use the view in queries instead of the raw tables.

What if the column names differ only by case in the schema?

SQL Server is case-insensitive for column names (unless in SQL Server 2016+ with case-sensitive collations). Use: SELECT * FROM ChildTable WHERE LOWER(foreign_key_column) = LOWER(ParentTable.primary_key) to handle case mismatches.

How do I debug a stored procedure with error 240?

Add this before the problematic query: SET SHOWPLAN_TEXT ON; GO EXEC YourProcedureName; GO SELECT * FROM sys.dm_exec_query_plan; GO SET SHOWPLAN_TEXT OFF; Then analyze the plan for explicit comparisons. Look for casts or implicit conversions in the WHERE clauses.

Is there a way to check for type mismatches without altering the database?

Use this script to generate a report of all potential mismatches:

SELECT
    t1.name AS Table1,
    c1.name AS Column1,
    t2.name AS Table2,
    c2.name AS Column2,
    CAST(t1.column_definition AS VARCHAR(MAX)) AS Table1Type,
    CAST(t2.column_definition AS VARCHAR(MAX)) AS Table2Type
FROM
    sys.columns c1
JOIN
    sys.tables t1 ON c1.object_id = t1.object_id
LEFT JOIN
    sys.columns c2 ON c2.object_id = OBJECT_ID('ParentTable')
    AND c2.name = 'foreign_key'
LEFT JOIN
    sys.tables t2 ON c2.object_id = t2.object_id
WHERE
    t1.name = 'ChildTable' AND t2.name = 'ParentTable'