How to Fix Error Converting Data Type Varchar to Bigint

To fix “Error converting data type varchar to bigint,” find the value or expression being converted, then either validate it as a numeric value or keep it as text throughout the operation. TRY_CAST helps identify values that cannot be converted without stopping the query, but replacing every failed conversion with NULL can hide a data problem. This guide covers SQL Server and related T-SQL environments, including errors caused by joins, inserts, application parameters, and reporting queries.

Use the symptom to narrow down where the conversion happens:

Symptom Likely Cause Fix
An explicit CAST fails on some rows Invalid characters, decimal text, or a value outside the bigint range Find the failing values with TRY_CAST, then correct or reject them
A join or comparison fails without an explicit cast SQL Server implicitly converts a text operand to bigint Make both operands use the intended data type
A URL, label, or combined result fails Mixed text and numeric types in +, CASE, or UNION Use CONCAT or explicitly return a consistent text type
A SELECT works, but an insert fails The destination column or another write operation requires bigint Inspect destination mappings and the complete insert path
The error appears only in an application or Power BI Parameter types, supplied values, or generated queries differ Reproduce and correct the actual application or refresh operation

Why SQL Server Raises This Conversion Error

varchar stores text. bigint stores whole numbers within a fixed range. A string containing letters, punctuation, a decimal representation, or an out-of-range integer may not convert to bigint.

The conversion does not have to appear explicitly in your SQL. SQL Server can introduce it through data-type precedence. Because bigint has higher precedence than varchar, SQL Server generally tries to convert the text operand to bigint when those types are compared.

For example, joining a text account number to a numeric account number can trigger the error even if the query contains no CAST.

Other places that establish a numeric requirement include:

  • A destination column in an insert or update.
  • A stored procedure parameter.
  • A branch of a CASE expression.
  • A corresponding output column in a UNION.
  • An arithmetic expression or overloaded + operator.

A difference between NULL and NOT NULL declarations does not, by itself, explain a varchar-to-bigint conversion. If both visible columns really are varchar, inspect the surrounding expressions, views, parameters, and destination schema.

How to Fix Varchar-to-Bigint Conversion Errors

The examples below use dbo.SourceData, with columns RowId and TextId, and dbo.TargetData, with a bigint column named Id. Replace those names with your actual tables and columns before running the queries.

Step 1: Locate the Conversion and Check the Actual Types

  1. Capture the complete failing SQL statement and its parameter values.
  2. Identify explicit casts and places where text meets a numeric column or expression.
  3. Inspect the source and destination definitions rather than relying on how values look in a results grid.

This query shows the declared types for the example tables:

SELECT
    OBJECT_SCHEMA_NAME(c.object_id) AS SchemaName,
    OBJECT_NAME(c.object_id) AS TableName,
    c.name AS ColumnName,
    t.name AS DataType,
    c.max_length AS MaxLengthBytes,
    c.is_nullable AS IsNullable
FROM sys.columns AS c
INNER JOIN sys.types AS t
    ON c.user_type_id = t.user_type_id
WHERE c.object_id IN (
    OBJECT_ID(N'dbo.SourceData'),
    OBJECT_ID(N'dbo.TargetData')
)
ORDER BY
    SchemaName,
    TableName,
    c.column_id;

Check expressions as well as stored columns. A view can expose a cast, and a temporary table created by a query can have a different type from the original source. Stored procedure parameters also need to match the values supplied by the caller.

Finish this step by identifying the expression SQL Server is trying to treat as bigint, not merely the table containing the text.

Step 2: Find Unconvertible Values Without Crashing the Query

  1. Preserve the original value in the diagnostic output.
  2. Normalize blank input separately from numeric conversion.
  3. Use TRY_CAST to return conversion failures as NULL.

For a permitted conversion such as ordinary varchar-to-bigint conversion, Microsoft’s TRY_CAST documentation specifies that a failed conversion returns NULL. That makes it useful for locating malformed or out-of-range values.

SELECT
    s.RowId,
    s.TextId AS OriginalValue,
    n.CleanText,
    CASE
        WHEN s.TextId IS NULL THEN 'Source NULL'
        WHEN n.CleanText IS NULL THEN 'Blank'
        ELSE 'Not convertible to bigint'
    END AS Issue
FROM dbo.SourceData AS s
CROSS APPLY (
    VALUES (NULLIF(LTRIM(RTRIM(s.TextId)), ''))
) AS n(CleanText)
CROSS APPLY (
    VALUES (TRY_CAST(n.CleanText AS bigint))
) AS p(BigintId)
WHERE p.BigintId IS NULL;

This deliberately reports three different conditions:

  • Source NULL: no value was supplied.
  • Blank: the value contains no text after ordinary surrounding spaces are removed.
  • Not convertible: text remains, but it cannot become a bigint.

Missing values are not necessarily errors if your schema permits them. Keep them separate from malformed identifiers when deciding what to reject.

The blank normalization matters because SQL Server can convert an empty string to numeric zero. The query treats it as missing instead. It does not remove tabs, nonbreaking spaces, punctuation, or other embedded characters.

Do not use ISNUMERIC as proof that a value fits bigint: it recognizes values valid for other numeric types too. A digits-only check also cannot detect an integer that is too large.

Likewise, do not rely on a filtering predicate to protect a separate hard CAST. SQL Server can reorder evaluation; putting the filter in a subquery or CTE does not guarantee that it executes first.

Step 3: Make the Comparison Match the Data’s Meaning

  1. Decide whether the field represents a numeric value or a text identifier.
  2. Use TRY_CAST on the text operand for numeric keys, or compare both operands as text for text identifiers.
  3. Check both matched and unmatched records before accepting the result.

For genuinely numeric keys, put the safe conversion directly in the comparison:

SELECT
    s.RowId,
    s.TextId,
    t.Id
FROM dbo.SourceData AS s
INNER JOIN dbo.TargetData AS t
    ON TRY_CAST(
        NULLIF(LTRIM(RTRIM(s.TextId)), '')
        AS bigint
    ) = t.Id;

An unconvertible source value becomes NULL and does not match this inner join. That prevents the conversion error, but it also excludes that source row. Review the diagnostic results and unmatched records so that an apparently successful query does not silently lose required data.

Numeric comparison also treats differently formatted versions of the same integer as equal. That is appropriate for numeric keys, but potentially wrong for identifiers whose leading zeros matter.

For text identifiers, keep the comparison textual. If one side is already stored as bigint, explicitly convert that side to text:

SELECT
    s.RowId,
    s.TextId,
    t.Id
FROM dbo.SourceData AS s
INNER JOIN dbo.TargetData AS t
    ON s.TextId = CONVERT(varchar(50), t.Id);

This compares the text against the numeric value’s decimal representation. A zero-padded identifier will not automatically match its unpadded version, and converting a stored number to text cannot restore zeros that were previously discarded.

Verify whether zero-padded identifiers should match their unpadded versions before accepting the join results. For a lasting fix, make identifier columns and their application parameters use a consistent text type and sufficient length.

Step 4: Decide What Happens to Rejected Values

  1. Correct values only when the intended value can be established from a trusted source.
  2. Reject or quarantine unresolved records, preserving their original text and identifying key.
  3. Run the corrected query against the complete input and reconcile accepted, rejected, and unmatched records.

Do not replace failed conversions with zero unless zero is explicitly the correct business value. Otherwise, unrelated invalid records can collapse onto the same key.

Also avoid indiscriminately removing nondigit characters. A minus sign, decimal separator, extension, or alphabetic prefix can carry meaning; stripping it can turn invalid input into a different, valid-looking number.

If every row must have a valid numeric key, stop the import when unresolved values remain. If partial acceptance is permitted, retain a reject record for every excluded row. The finished result should explain where every source record went.

Common Query Patterns That Need a Different Fix

Text Concatenation With a Numeric Value

SQL Server’s + operator can mean addition or concatenation. When a string and a bigint are mixed, type precedence can cause SQL Server to attempt numeric conversion rather than produce a string.

For a URL or display label, use CONCAT:

SELECT
    CONCAT(
        'https://example.com/providers/',
        t.Id
    ) AS ProviderUrl
FROM dbo.TargetData AS t;

CONCAT converts the numeric argument to text for concatenation. Check the resulting URLs against the expected identifier representation before using them.

Remember that CONCAT treats NULL arguments as empty strings. If a missing identifier should produce no URL, handle that condition explicitly rather than accepting a URL containing only the prefix.

Mixed Types in CASE and UNION

A CASE expression has a result type determined from its branches. Returning a numeric ID in one branch and a label in another can make SQL Server attempt to convert the label to a number.

Make both branches textual:

SELECT
    CASE
        WHEN t.Id IS NULL THEN 'Unknown'
        ELSE CONVERT(varchar(50), t.Id)
    END AS IdLabel
FROM dbo.TargetData AS t;

Run the query with both missing and populated IDs to confirm the output.

For UNION or UNION ALL, inspect each corresponding output column across all participating queries. If the combined column is intended to contain labels and identifiers, explicitly convert numeric branches to a suitable text type before combining them. Test the complete combined query, not just each branch separately.

Phone Numbers and Other Formatted Identifiers

Phone numbers, fax numbers, postal codes, and account identifiers are often better represented as text. They can contain leading zeros, country prefixes, separators, or extensions that a numeric type cannot preserve.

Do not cast a phone number to bigint merely to add display punctuation. Keep the underlying value as text, validate it against the supported numbering format, and format it in a presentation layer or a string-based expression appropriate to that format.

Check examples containing leading zeros, prefixes, extensions, and missing values. A successful numeric cast is not evidence that the phone number has been represented correctly.

When the Error Only Appears in an Insert or Application

A successful standalone conversion does not prove that the insert or application execution path is type-correct.

Inserts Into a Separate Table

An operation that succeeds alone may fail when it also inserts data into another table. The destination introduces another set of type requirements, and triggers or computed expressions can introduce additional conversions.

Inspect:

  • The destination column types.
  • The correspondence between insert columns and selected expressions.
  • Any omitted insert column list.
  • Defaults, computed columns, and triggers involved in the write.

Use an explicit destination column list so that the mapping is intentional. A misplaced expression can send text into a numeric column even when the source query itself is valid.

Test the entire insert against a test destination, including any downstream writes. Confirm the inserted values and reconcile the write count with the accepted source records before deploying the change.

Stored Procedures Called From .NET

A stored procedure may return a conversion error when called from a .NET web application even though a manually constructed call succeeds. Reproduce the application call using its actual argument values and SQL parameter types.

For a numeric parameter:

  • Validate textual input with long.TryParse before making the database call.
  • Bind the parsed .NET long using SqlDbType.BigInt.
  • Pass database nulls using DBNull.Value when the parameter permits them.

For a text identifier, use a matching text declaration in both the procedure and the application parameter, with an explicit appropriate length. Do not let a numeric-looking sample value determine the intended type.

Retest through the application with valid input, invalid text, missing input, and an out-of-range value. Invalid input should be rejected deliberately, not passed through until SQL Server raises a conversion exception.

Power BI Refreshes

When Power BI surfaces SQL Server’s varchar-to-bigint error, inspect both the SQL source and Power Query transformations. Type changes and merges can introduce a numeric requirement, and query folding may push that conversion into SQL Server.

Keep identifier columns as text when their formatting matters. For genuinely numeric columns, inspect conversion errors and correct or reject the source values rather than removing all error rows without accounting for them.

Validate the fix with a complete refresh. A preview can succeed simply because it does not include the failing records.

How to Verify and Prevent the Conversion Error

A query that no longer throws an exception is only part of the verification. Confirm that it still produces the right data:

  • Conversion exceptions are accounted for: malformed values are corrected or retained in a reject output.
  • Missing values remain distinct: blanks and source nulls follow the intended business rule.
  • Matches are correct: numeric normalization has not merged identifiers that should remain separate.
  • The full operation succeeds: inserts, application calls, and refreshes work through their actual execution paths.
  • Counts reconcile: source records are accounted for as accepted, rejected, or intentionally unmatched.

For recurring imports, land raw text in a staging area, validate it, and move accepted values into properly typed columns. Preserve rejected input so it can be corrected without guessing what the original value contained.

Align join columns and parameter types wherever possible. Repeated conversion of join or filter columns can prevent efficient index seeks; a validated, indexed numeric key is generally a better long-term design than converting raw text during every query.

Once these checks pass, rerun the original failing operation end to end and deploy the change with reject handling intact.

Frequently Asked Questions

How Do I Fix “Error Converting Data Type Varchar to Numeric”?

Convert to the numeric type the data actually requires, using an appropriate precision and scale for decimal values. Use TRY_CAST against that target type to identify malformed or out-of-range input before writing it. Do not switch to bigint merely to avoid the error if fractional values are meaningful.

Why Does EOMONTH Produce a Conversion Error?

EOMONTH expects a date expression as its first argument and an optional integer month offset as its second argument. Supplying a date string as the offset, or treating a numeric identifier as a date, can trigger a conversion failure. Validate the date expression separately, then supply a whole-number offset only when you intend to shift the month.

Can I Use TRY_CAST to Fix This in Microsoft Fabric?

In Microsoft Fabric Warehouse and a Lakehouse SQL analytics endpoint, TRY_CAST can help diagnose varchar-to-bigint failures in T-SQL queries. A Lakehouse SQL analytics endpoint does not let you update the underlying Delta table through T-SQL, so permanent data corrections belong in the lakehouse or its ingestion process. If the failure comes from a Spark notebook instead, inspect the Spark operation and its type rules rather than assuming SQL Server behavior.

Why does formatting a varchar value as bigint fail in SQL Server?

A bigint conversion used for formatting fails when at least one varchar input contains a value that bigint cannot accept. Use TRY_CAST while examining the source values so entries that cannot convert appear as NULL instead of stopping the query.