简体   繁体   中英

Stored Procedure Error Arithmetic overflow error converting numeric to data type varchar

I know this question has been asked so many times. But I googled a lot and also went through the answers over here but couldn't able to understand why my stored Procedure is giving this error repeatedly since little while ago the same code was perfectly working fine.

Please any one can help my identify that why this error is coming. Also Even if when this was working I was not getting my desired output as I want to generate the order numbers in sequence but I'm getting the same number as the number of count.

USE [Sost_Dev]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [sost].[GetExternalOrderNumbers]
    @Count int
AS
BEGIN
    SET NOCOUNT ON;
DECLARE @year VARCHAR(2)
DECLARE @ExternalOrderNumbers nvarchar(50)

SET @year = RIGHT(CAST(DATEPART(yy, GETUTCDATE()) AS VARCHAR(4)),2)

    -- Insert statements for procedure here
BEGIN TRAN
SAVE TRAN seq

            --Creating Temp Table for every isolated connection
            CREATE TABLE #NewOrders(ExtOrderNumber nvarchar(50));

            WHILE @Count > 0
                BEGIN
                   INSERT INTO [sost].ServiceOrderNumberSequence DEFAULT VALUES
                    SET @ExternalOrderNumbers = 'ESON' + @year + RIGHT(REPLICATE('0',10) + CAST(SCOPE_IDENTITY() AS  NVARCHAR(7)) ,7);
                    print 'External' + @ExternalOrderNumbers;
                    --Insert New Order Number to Temporary Tables
                   INSERT INTO #NewOrders  values(@ExternalOrderNumbers)
                   SET @Count -=1
                END

COMMIT

--Fetching Order Numbers from Temporary Table.

SELECT @ExternalOrderNumbers as ExternalOrderNumber from #NewOrders
END

Please see the below image for the error in my SQLServer在此处输入图片说明

在此处输入图片说明

Please find the result All the order numbers are same but I want in consecutive manner. 在此处输入图片说明

Just change this line

SET @ExternalOrderNumbers = 'ESON' + @year + RIGHT(REPLICATE('0',10) + CAST(SCOPE_IDENTITY() AS  NVARCHAR(100)) ,7);

Edit: AS per your requirement.

SET @ExternalOrderNumbers = 'ESON' + @year + RIGHT(REPLICATE('0',10) + CAST(RIGHT(SCOPE_IDENTITY(),7) AS  NVARCHAR(7)) ,7);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM