Conversion failed when converting the varchar value 'BB-2' to data type int.

Analyst_SQL 3,486 Reputation points
2021-02-18T11:27:46.103+00:00

I am inserting BB-1 ,then again ,BB-2 is generating , it is giving error.

Conversion failed when converting the varchar value 'BB-2' to data type int.

CREATE TABLE #tbl_Sell_M(Bill_No varchar(10),E_Date date)




WITH cte AS (SELECT 1 AS Bill_No
                          UNION ALL
                          SELECT TOP (1) Bill_No + 1 AS Bill_No
                          FROM     dbo.tbl_Sell_M AS t
                          ORDER BY Bill_No DESC)
    SELECT TOP (1)  CONCAT('BB-', Bill_No)  AS Bill_No
    FROM     cte
    ORDER BY Bill_No DESC
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
11,592 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,458 questions
{count} votes

Accepted answer
  1. Viorel 106.4K Reputation points
    2021-02-18T11:49:02.503+00:00

    If tbl_Sell_M is empty then it works. But if it contains something like ‘BB-1’ or ‘BB-2’, then it is not possible to calculate Bill_No + 1.

    Consider using integers (int column) without ‘BB-‘ (which can be prepended later), or try this workaround, which is probably less recommended:

    WITH cte AS (SELECT 1 AS Bill_No
                               UNION ALL
                               SELECT TOP (1) stuff(Bill_No, 1, 3, '') + 1 AS Bill_No
                               FROM     tbl_Sell_M AS t
                               ORDER BY Bill_No DESC)
         SELECT TOP (1)  CONCAT('BB-', Bill_No)  AS Bill_No
         FROM     cte
         ORDER BY Bill_No DESC
    
    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Olaf Helper 36,091 Reputation points
    2021-02-18T11:34:28.273+00:00

    Please post table design of the table as DDL, some sample data as DML and the expected result.
    .
    By the error message you try to mix varchar & int values; that don't work in SQL, you have to convert the values to same data type.


  2. Olaf Helper 36,091 Reputation points
    2021-02-18T11:46:50.467+00:00

    CREATE TABLE #tbl_Sell_M( Bill_No varchar(10) ,E_Date date)

    As expected, Bill_No is of type varchar, you can not "add" numeric 1 on the values. How does the existing data (=samples, as requested) look like?

    0 comments No comments