2016-10-03 78 views
0

表tblidset在第一次運行時不包含任何內容,那麼當我在代碼中第一次調用此存儲過程時,它應該從表中獲取最高值,以便構建值隨着程序數據的增長而變化。錯誤的問題是它在第一次運行時總是返回0。現在困住了幾個小時。關心幫助?這是我的腳本:我的存儲過程總是返回0

CREATE PROCEDURE CREATENEWID 
@TYPE AS INT 
AS 
BEGIN 

DECLARE @CNT AS INT; 
DECLARE @DOCNO AS BIGINT; 
DECLARE @DOCID AS BIGINT; 
SELECT @CNT = ISNULL(COUNT(*),0) FROM TBLIDSET 

--CHECK IF THERE IS NO VALUE AS OF DATE AND INSERT DEFAULT VALUES 
    IF @CNT = 0 

    BEGIN 

     INSERT INTO TBLIDSET SELECT TOP 1(DOCID),0 FROM INVHDR ORDER BY DOCID DESC 
    END 
    DECLARE @NUM AS INT; 
    IF @TYPE = 1 
     BEGIN 
      UPDATE TBLIDSET SET DOCID = DOCID +1 
      SELECT @NUM = DOCID FROM TBLIDSET 
     END 
    ELSE 
     BEGIN 
      UPDATE TBLIDSET SET DOCNO = DOCNO + 1 
      SELECT @NUM = DOCNO FROM TBLIDSET 
    END 
    PRINT @NUM 
    RETURN @NUM 

END 
GO 
+1

你爲Type參數傳遞了什麼? – Steve

+0

使用'MAX + 1'作爲ID是一個*問題*,因爲它很容易導致重複的值。此外,此代碼不會查找*最大* ID,它只會返回一個隨機數。 'SELECT @NUM = DOCID FROM TBLIDSET'可返回任何*的底層值 –

+0

而不是嘗試生成自己的序列,請使用SQL Server的[SEQUENCE](https://msdn.microsoft.com/en-us/library /ff878058.aspx)功能,自SQL Server 2012起可用。您使用的是哪個版本? –

回答

0

請試試這段代碼。我將輸出參數添加到您的代碼中。

CREATE PROCEDURE CREATENEWID 
@TYPE AS INT, 
@NUM AS INT OUT --Declare ouput parameter here 
AS 
BEGIN 

DECLARE @CNT AS INT; 
DECLARE @DOCNO AS BIGINT; 
DECLARE @DOCID AS BIGINT; 
SELECT @CNT = ISNULL(COUNT(*),0) FROM TBLIDSET 

--CHECK IF THERE IS NO VALUE AS OF DATE AND INSERT DEFAULT VALUES 
    IF @CNT = 0 

    BEGIN 

     INSERT INTO TBLIDSET SELECT TOP 1(DOCID),0 FROM INVHDR ORDER BY DOCID DESC 
    END 
    --Move your @NUM to output parameter 
    IF @TYPE = 1 
     BEGIN 
      UPDATE TBLIDSET SET DOCID = DOCID +1 
      SELECT @NUM = DOCID FROM TBLIDSET 
     END 
    ELSE 
     BEGIN 
      UPDATE TBLIDSET SET DOCNO = DOCNO + 1 
      SELECT @NUM = DOCNO FROM TBLIDSET 
    END 
    PRINT @NUM 
    RETURN @NUM 

END 
GO 
+0

爲什麼這會有所作爲? 'RETURN'沒有損壞。如果'@ NUM'有一個值'RETURN'將返回它。 –

+0

我認爲他的第一次運行結果是執行結果代碼。 0就是成功。我想通過OUT參數來幫助他。 –