我通过where子句和数量和角色(更新或减少数量)。
我的存储过程是:
ALTER PROCEDURE [dbo].[spUpdateQuantity]
(
@WhereClause AS NVARCHAR,
@Qty AS INT,
@Role AS INT
)
AS
BEGIN
DECLARE @CurrentQty AS INT;
SELECT @CurrentQty = Quantity
FROM ProductMaster
WHERE SKUCode = @WhereClause;
IF(@Role = 1)
BEGIN
UPDATE ProductMaster
SET Quantity = (@CurrentQty + @Qty)
WHERE SKUCode = @WhereClause;
END
IF(@Role = 2)
BEGIN
UPDATE ProductMaster
SET Quantity = (@CurrentQty - @Qty)
WHERE SKUCode = @WhereClause;
END
END
目前的状态是
=====================================================
| ProductId | SKUCode | Quantity |
------------------------------------------
| GA10000005 | GA.42205 | 5 |
使用查询命令我更新状态,如...
DECLARE @return_value int
EXEC @return_value = [dbo].[spUpdateQuantity]
@WhereClause = N'GA.42205',
@Qty = 3,
@Role = 1
SELECT 'Return Value' = @return_value
GO
我的结果为0 ,状态与之前相同
有没有人有想法以这种方式更新库存数量?
答案 0 :(得分:3)
如果要获取某个值而不是使用返回值,那么您应该将OUTPUT
变量添加到存储过程,这是为了返回执行proc的状态:
ALTER PROCEDURE [dbo].[spUpdateQuantity]
(
@WhereClause AS NVARCHAR(100),
@Qty AS INT,
@Role AS INT,
@NewQty INT OUTPUT
)
AS
BEGIN
DECLARE @CurrentQty AS INT;
SELECT @CurrentQty = Quantity FROM ProductMaster WHERE SKUCode = @WhereClause;
IF(@Role = 1)
BEGIN
SET @NewQty = @CurrentQty + @Qty
UPDATE ProductMaster
SET Quantity = @NewQty
WHERE SKUCode = @WhereClause;
END
IF(@Role = 2)
BEGIN
SET @NewQty = @CurrentQty - @Qty
UPDATE ProductMaster
SET Quantity = @NewQty
WHERE SKUCode = @WhereClause;
END
END
并使用它:
DECLARE @return_value int, @NewQty INT
EXEC @return_value = [dbo].[spUpdateQuantity]
@WhereClause = N'GA.42205',
@Qty = 3,
@Role = 1,
@NewQty = @NewQty OUTPUT
SELECT @NewQty AS 'Return Value'
结果是0。问题的第二部分是显而易见的:将类型更改为@WhereClause AS NVARCHAR(100)
。其他方式,它被视为@WhereClause AS NVARCHAR(1)
,您传递的值被截断为N'G'
。
https://msdn.microsoft.com/en-us/library/ms186939.aspx
nvarchar [(n | max)] 在数据定义或变量声明中未指定n时 声明,默认长度为1.使用时未指定n CAST和CONVERT函数,默认长度为30。
答案 1 :(得分:0)
这应该有效:
ALTER PROCEDURE [dbo].[spUpdateQuantity]
(
@WhereClause AS NVARCHAR,
@Qty AS INT,
@Role AS INT
)
AS
BEGIN
UPDATE ProductMaster
SET Quantity = Quantity + case when @Role = 1 then @Qty else (@Qty*-1) end
WHERE SKUCode = @WhereClause;
END
答案 2 :(得分:0)
你能完全删除@role并以正数或负数调用它吗?
ALTER PROCEDURE [dbo].[spUpdateQuantity]
(
@SKUCode AS NVARCHAR,
@Qty AS INT
)
AS
BEGIN
UPDATE ProductMaster
SET Quantity = Quantity + @Qty
WHERE SKUCode = @SKUCode;
END
还将@WhereClause重命名为@SKUCode,因为它更容易理解它是什么。