SQL Server Error 402: Data Types Incompatible Fix Guide
In this article
SQL Server Error 402 occurs when you attempt to perform an operation—like a comparison, assignment, or arithmetic calculation—between two columns or values with incompatible data types. This is not a syntax error but a type mismatch, and it stops execution immediately. The fix requires identifying the mismatched types and explicitly converting one to match the other using CAST or CONVERT. No external tools are needed—this is resolved within your SQL script using built-in functions.
What You'll Need
- Access to SQL Server Management Studio (SSMS) or another SQL client connected to your database
- Permission to run SELECT, UPDATE, INSERT, or DELETE statements on the affected tables
- The exact error message text, including the line number and the two data types involved (e.g., "int" and "varchar")
- A backup of your data if modifying tables (recommended before bulk updates)
Step-by-Step
- Locate the exact SQL statement causing the error. The error message usually includes the line number and object name. Open the query window in SSMS and scroll to that line.
- Identify the two data types involved. The error message says something like "The data types varchar and int are incompatible in the add operator." Note both types: one is likely a string or date, the other a number or datetime.
- Check the columns or variables being used. For example, if you're writing WHERE Age = '25', and Age is an INT column, you're comparing an integer to a string. Look at the schema: right-click the table in SSMS > Properties > Columns to confirm data types.
- Use CAST or CONVERT to explicitly convert one value to match the other. For example, change WHERE Age = '25' to WHERE Age = CAST('25' AS INT) or WHERE Age = CONVERT(INT, '25'). Always convert the literal or variable, not the column, to avoid index performance issues.
- If joining tables, ensure the join keys have compatible types. If joining TableA.ID (INT) to TableB.Code (VARCHAR), change the join to ON TableA.ID = CONVERT(INT, TableB.Code) — but only if TableB.Code contains only numeric values. Test with SELECT DISTINCT Code FROM TableB WHERE ISNUMERIC(Code) = 0 to find invalid entries first.
- For date comparisons, avoid string literals like WHERE OrderDate = '2023-12-01'. Use CONVERT(DATE, '2023-12-01') or better yet, use a proper DATE type variable. SQL Server may implicitly convert, but it’s unreliable and triggers Error 402 in strict settings.
- If using a function like SUM or AVG on a VARCHAR column, wrap it with CAST: SUM(CAST(SalesAmount AS DECIMAL(10,2))). Never assume numeric data stored as text will auto-convert.
- After making changes, test the query on a small dataset first. Run it with TOP 10 or a WHERE clause limiting rows to verify correctness before applying to full tables.
- Once confirmed, update stored procedures, views, or triggers with the corrected logic. Avoid leaving implicit conversions in production code — they break under different collations or server settings.
Common Mistakes
- Trying to compare a VARCHAR column directly with an INT without conversion, assuming SQL Server will do it automatically — it often won’t, especially with SET ANSI_NULLS or ARITHABORT enabled.
- Using ISNUMERIC() as a reliable check for numeric strings — it returns 1 for values like '$', ',', or '1e3', which still cause conversion errors when CAST is applied.
- Converting a column instead of a literal (e.g., CONVERT(INT, ColumnName) in WHERE clauses) — this prevents index usage and slows queries dramatically.
- Assuming date formats like '01/12/2023' will work universally — the interpretation depends on language settings. Always use YYYY-MM-DD for unambiguous dates.
- Using string concatenation in arithmetic: SELECT '100' + 50 — this fails because SQL Server tries to convert the string to a number, but if the string contains non-numeric characters, it throws Error 402.
Tips
- Use TRY_CAST or TRY_CONVERT instead of CAST or CONVERT when you suspect invalid data. These return NULL instead of an error, letting you handle bad values gracefully.
- Enable SET STATISTICS IO ON before running queries to see if implicit conversions are occurring — they appear as warnings in the Messages tab.
- When designing tables, avoid storing numbers or dates as VARCHAR unless absolutely necessary. It invites type mismatches and degrades performance.
- Use aliases in complex queries to clarify which values are being converted: SELECT CAST(CustomField AS INT) AS NumericValue — this improves readability and debugging.
- For ETL processes, validate data types in staging tables before inserting into production. Use a staging step with CHECK constraints or a data quality script.
- Document data type expectations in your team’s coding standards. Include examples of correct conversions for common scenarios like phone numbers, ZIP codes, or currency strings.
Troubleshooting
If the error persists after conversion:
- Check for leading/trailing spaces or non-breaking characters in string data. Use LTRIM(RTRIM(ColumnName)) before conversion.
- Test the problematic column with SELECT TOP 100 ColumnName FROM TableName WHERE ColumnName IS NOT NULL AND ColumnName != '' to find hidden values.
- If converting VARCHAR to INT or DECIMAL, run a query to find invalid entries: SELECT ColumnName FROM TableName WHERE ISNUMERIC(ColumnName) = 0 AND ColumnName IS NOT NULL. Fix or exclude these rows.
- Verify collation settings aren’t causing silent failures. Run SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation') to confirm collation matches expected sorting rules.
- If the error occurs in a stored procedure, recompile it: EXEC sp_recompile 'YourProcedureName'. Sometimes cached execution plans retain old type assumptions.
- Temporarily disable ANSI_WARNINGS with SET ANSI_WARNINGS OFF to see if the issue is related to strict mode — but only for diagnostics; never leave it disabled in production.
- If using linked servers, ensure remote data types are correctly mapped. Use OPENQUERY with explicit CASTs if the remote server is Oracle or MySQL.
Frequently Asked Questions
Why does SQL Server sometimes let me compare a string and a number without error?
SQL Server performs implicit conversions in some contexts, especially in simple SELECT statements. But when ARITHABORT, ANSI_NULLS, or compatibility levels are set strictly (like in modern databases), it refuses implicit conversions to prevent silent data loss.
Can I use TRY_CAST to avoid Error 402 entirely?
Yes. TRY_CAST returns NULL if the conversion fails, so it prevents the error. Use it in WHERE clauses like WHERE TRY_CAST(strCol AS INT) > 100. Combine with IS NULL checks to handle bad data.
What if the data type mismatch is in a view or computed column?
Alter the view or computed column definition to include explicit CAST or CONVERT. You must drop and recreate the view if the schema changes. Use ALTER VIEW with the corrected logic.
Why does Error 402 happen only sometimes, even with the same query?
It may depend on data content. If a query runs fine on 100 rows but fails on 1000, it’s likely because one row contains non-numeric text. Use a cursor or batch test to isolate the problematic record.
Can I change a column’s data type to fix this permanently?
Yes, but only if all existing data is valid. Use ALTER COLUMN ColumnName INT — but first back up the table and test with a small sample. If any values can’t convert, the ALTER will fail.
Is this error related to SQL Server version?
No. Error 402 has existed since SQL Server 7.0 and behaves consistently across versions. It’s a core type-safety rule, not a bug or version-specific behavior.