我编写了应该返回值的存储过程 -
J1
J2
J3
我有表名为Journal_Entry
. 当表的行数为 0 时,它会给出结果J1
,但随着行数的增加,它会显示错误-
"Conversion failed when converting the varchar value 'J' to data type int."
#这里Voucher_No
是要保存结果的列。
代码就像 -
CREATE PROC [dbo].[getVoucherNo]
AS
BEGIN
DECLARE @Prefix VARCHAR(10)='J'
DECLARE @startFrom INT=1
DECLARE @maxCode VARCHAR(100)
DECLARE @sCode INT
IF((SELECT COUNT(*) FROM dbo.Journal_Entry) > 0)
BEGIN
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,LEN(Voucher_No)- LEN(@Prefix)) AS INT)) AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)
SELECT @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))
END
ELSE
BEGIN
SELECT(@Prefix + CAST(@startFrom AS VARCHAR))
END
END