从表中选择最大值,并在存储过程中使用If Else Condition设置值

时间:2014-07-23 05:28:03

标签: database stored-procedures insert sql-server-2012-express

我想将数据插入到存储过程中。有条件我想要满足。Select Max value from OF Table Field "OurRef" From Table "tblPurchaseInvoice" Where SupplierID=SomeID.Then If OurRef>0然后要插入的值是OurRef+1 Else Set Vale OurRef=100。我写了存储程序但它不起作用。谢谢你.Below

ALTER PROCEDURE [dbo].[addPurchaseInvoicing]
(
 @JobID int = null,
 @InvoiceDate datetime,
 @SupplierID int,
 @SuppliersInvoiceNumber VARCHAR(40),
 @PurchaseOrderRef varchar(20),
 @Type tinyint,
 @Paid tinyint,
 @ReferencePurchaseInvoiceID tinyint = null
)
AS
DECLARE @ID INT = 0;
DECLARE @OURREF AS INT=0;
BEGIN
 IF  ((select MAX(OurRef) from tblPurchaseInvoice where SupplierID=@ID)=NULL)
 BEGIN
  SET @OURREF='100'
 END
 ELSE IF(@OURREF>'0')
  BEGIN
   SET @OURREF='100'+'1'
  END
BEGIN 
    INSERT INTO tblPurchaseInvoice(
        JobID,
        InvoiceDate,
        SupplierID, 
        OurRef,
        SuppliersInvoiceNumber,
        PurchaseOrderRef,   
        [Type],     
        Paid,
        ReferencePurchaseInvoiceID,
        OurRef
       )
VALUES (
        @JobID,
        @InvoiceDate,
        @SupplierID,
        @OurRef,
        @SuppliersInvoiceNumber,
        @PurchaseOrderRef,
        @Type,
        @Paid,
        @ReferencePurchaseInvoiceID,
        @OURREF
 );
 SET @ID = @@IDENTITY;
END
RETURN @ID
END

1 个答案:

答案 0 :(得分:0)

不确定这是否是它不起作用的主要原因,而是使用 (Value = NULL)而不是(Value IS NULL)可能会导致一些问题

((select MAX(OurRef) from tblPurchaseInvoice where SupplierID=@ID)=NULL) 

可以改写为:

((select MAX(OurRef) from tblPurchaseInvoice where SupplierID=@ID) IS NULL)

= NULL vs. IS NULL