2017-03-27 51 views
1

嗨我有一個存儲過程的輸出參數,其值必須從兩個內部選擇語句中返回。我有@nTotalRecords作爲我的輸出參數值將來自以下select語句應該怎麼檢索表的別名TBL輸出參數在這種情況下,我想這樣的從具有多個返回值的select語句中檢索輸出參數值以及其他返回值

create procedure [usp_GetMessagesbyReferenceID1] 
(  
@nRowsPerPage    int, 
@nPage      int, 
@nTotalRecords    int output 
) as 
select 
    TBL.createdate, 
    TBL.templateid, 
    @nTotalRecords=TBL.TotalRecords 
    from 
    (
      select 
        message.createdate, 
        message.templateid, 
        count(1) over() as TotalRecords 
      from 
        nts.Messages as [message]  
    ) as TBL 

我試圖這樣說來設置輸出參數但它不工作它是拋出以下錯誤A SELECT statement that assigns a value to a variable must not be combined with data retrieval operations.有沒有可能實現這一點。 ?或者我在語法上犯了任何錯誤,請幫助我。

注: 從select語句的輸出參數的檢索工作正常,如果它僅返回一個值(輸出參數值),但我的要求是它應能正常工作時,我的select語句返回多個值(包括輸出參數)。

+0

標記您正在使用的dbms。該代碼是特定於產品的。 – jarlh

+0

@jarlh相應地添加了標籤 – Meena

+0

@MarekGrzenkowicz我的要求是返回 – Meena

回答

1

我已經嘗試了很多征服這一點,但atlast我已經通過這樣的方式來實現這一點,我已經寫了一個更select語句,以獲得總記錄數。我不確定答案是否完美和有效,但它對我來說工作得很好。請讓我知道是否有其他方法。

create procedure [usp_GetMessagesbyReferenceID1] 
(  
@nRowsPerPage    int, 
@nPage      int, 
@nTotalRecords    int output 
) as 
select 
    TBL.createdate, 
    TBL.templateid 
from 
    (
     select 
     message.createdate, 
     message.templateid 
     from 
     nts.Messages as [message]  
    ) as TBL 

select 
    @nTotalRecords = count(1) 
from 
    nts.Messages as [message] 
0
select 
    @CreatedDate=TBL.createdate, 
    @nTotalRecords=TBL.TotalRecords 
    from 
    (
      select 
        message.createdate, 
        count(1) over() as TotalRecords 
      from 
        nts.Messages as [message] 

    ) as TBL 

你的代碼應該是這樣的。刪除了選擇中的第1列。這將工作考慮內部查詢返回TotalRecords只有一個值。如果它返回多個,那麼最後的值將被分配給@nTotalRecords

+0

我正在檢索更多的值,並在分配最後一個值時顯示所提到的錯誤消息。我在答覆中錯過了某個點嗎?讓我知道。 – Meena

+0

@Meena,你試過我的代碼嗎?這不應該給任何錯誤。讓我知道你是否仍然有任何錯誤。 –

+0

我的要求是返回createdate和輸出參數,但在你的代碼中,你只返回輸出參數 – Meena

0

根據討論,以下代碼將幫助您獲取TotalRecords(int爲單值)和CreatedDate(以逗號分隔日期值的字符串)。

create procedure [usp_GetMessagesbyReferenceID1] 
(  
@nRowsPerPage    int, 
@nPage      int, 
@nTotalRecords    int output, 
@CreatedDate     varchar(500) output 
) as 

select @CreatedDate= 
    STUFF ((SELECT ','+ CAST(T.dates as varchar(15)) 
      FROM nts.Messages T 
      FOR XML PATH('')),1,1,'') 
select @nTotalRecords=TBL.TotalRecords  
from 
    (select dates, count(1) over() as TotalRecords 
     from nts.Messages 
    ) as TBL 
相關問題