我有一个存储过程:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spInsertNewPacks]
@T_ID INT OUT,
@BatchNumber VARCHAR(30) OUT,
@Count INT OUT
AS
BEGIN
DECLARE @I INT = 1
DECLARE @ID INT = 0
DECLARE @ID1 VARCHAR(50)
DECLARE @PackID VARCHAR(50)
SELECT @PackID = MAX(PackID)
FROM tblPacks
WHILE @I <= @Count
BEGIN
IF @PackID IS NULL
BEGIN
SET @I = @I + 1
SET @ID = @ID + 1
INSERT INTO tblPacks (T_ID, BatchNumber, PackID, Status)
VALUES (@T_ID, @BatchNumber,
CAST(('PK'+ (CASE WHEN len(@ID) <=3 THEN CAST(RIGHT(0.001 * @ID, 3) AS VARCHAR(20)) ELSE CAST(@ID AS VARCHAR(20)) END)) as VARCHAR(50)), 0)
END
ELSE
BEGIN
SELECT @ID1 = CONVERT(VARCHAR(50), MAX(PackID)) FROM tblPacks
SET @I = @I + 1
SET @ID = @ID + 1
SELECT MAX(PackID) as ID FROM tblPacks
INSERT INTO tblPacks (T_ID, BatchNumber, PackID, Status)
VALUES (@T_ID, @BatchNumber,
--CAST(('PK'+ (CASE WHEN len(@ID1) <=3 THEN CAST(RIGHT(0.001*@ID1, 3) AS VARCHAR(20)) ELSE CAST(@ID1 AS VARCHAR(20)) END)) as VARCHAR(50))
('PK'+ (CASE WHEN len(@ID1) <=3 THEN CAST(RIGHT(0.001*@ID1, 3) AS VARCHAR(20)) ELSE CAST(@ID1 AS VARCHAR(20)) END)), 0)
END
END
END
然后我写道:
EXEC spInsertNewPacks 1, '101', 4
得到了这个输出:
T_ID BatchNumber PackID Status
1 101 PK001 0
1 101 PK002 0
1 101 PK003 0
1 101 PK004 0
它运行正常,但是当我写了另一个EXEC命令时:
EXEC spInsertNewPacks 2, '102', 3
我得到了:
T_ID BatchNumber PackID Status
1 101 PK001 0
1 101 PK002 0
1 101 PK003 0
1 101 PK004 0
2 102 PKPK004 0
2 102 PKPKPK004 0
2 102 PKPKPKPK004 0
但必须是:
T_ID BatchNumber PackID Status
1 101 PK001 0
1 101 PK002 0
1 101 PK003 0
1 101 PK004 0
2 102 PK005 0
2 102 PK006 0
2 102 PK007 0
我哪里出错 - 任何想法?我尝试将ID声明为@ ID1作为varchhar,但它没有工作
答案 0 :(得分:2)
您只需要更改一个句子:
ng-if
要
SELECT @ID1=CONVERT(VARCHAR(50),MAX(PackID)) FROM tblPacks
并且
SELECT @ID = CONVERT(VARCHAR(50),MID(MAX(PackID),4)) FROM tblPacks
这对你有用。
答案 1 :(得分:0)
在你的Else陈述中,你有如下逻辑:
SELECT @ID1=CONVERT(VARCHAR(50),MAX(PackID)) FROM tblPacks
这将为您提供varchar(string)值,如:PK004
然后用“PK”附加它后面的结果为:PKPK004
('PK'+ (CASE WHEN len(@ID1) <=3 THEN CAST(RIGHT(0.001*@ID1, 3) AS VARCHAR(20)) ELSE CAST(@ID1 AS VARCHAR(20)) END))
结论:我认为您必须在else语句中使用@ID
而不是@ID1
,因此它会为您提供正确的输出
答案 2 :(得分:0)
在你的Else陈述中,你有如下逻辑:
SELECT @ID = CONVERT(VARCHAR(50), replace(MAX(PackID),'PK','')) FROM tblPacks
并且PackID的值也从@ ID1更改为@ID
('PK'+ (CASE WHEN len(@ID) <=3 THEN CAST(RIGHT(0.001*@ID, 3) AS VARCHAR(20)) ELSE CAST(@ID AS VARCHAR(20)) END)), 0)
因为我无法编辑上述答案。所以我添加新的答案请参考这个。