2017-06-23 58 views
0

我還是新的存儲過程。在存儲過程中執行時語法不正確返回

任何人都可以幫助並告訴我這有什麼問題嗎?

Create PROCEDURE [dbo].[spCreateProductionReport] 

@whereClause nvarchar(max) 

As 
Begin 
    declare @id int, @itemNum nvarchar(20), @datetimestamp datetime, @tStations_id int 
    declare @counter int, @itemNumPrev nvarchar(20) 
    set @counter = 0 
    set @itemNumPrev ='' 
    set @whereClause = '' 
    SET NOCOUNT ON; 
    create table #Temp 
    (
    id int, 
    itemNum nvarchar(20), 
     tStations_id int, 
     datetimestamp datetime, 
     groupID int 



    ) 


    DECLARE db_cursor CURSOR FOR 

    select id,itemNo,tstations_id,datetimestamp 
    from 
    tProduction_Count @whereClause 
    --where datetimestamp between '2017-03-16 00:00:00' and '2017-03-16 23:59:59' 
    ORDER BY id ASC 

    OPEN db_cursor 
    FETCH NEXT FROM db_cursor INTO @id, @itemNum,@tStations_id, @datetimestamp 

我得到的錯誤是: '消息102,級別15,狀態1,過程spCreateProductionReport,行42 附近有語法錯誤@WhereClause'。'

+0

@whereClause變量是一個參數,還是你忘記'聲明'它? – Norsk

+0

它應該是一個參數,我將使用whereClause從前端獲取字符串/文本並將其用作此處的篩選器 – MichaelJ

回答

0

你必須DECLARE變量第一

DECLARE @whereClause nvarchar(max)

而且,這不看的權利:select id,itemNo,tstations_id,datetimestamp from tProduction_Count @whereClause

什麼whereClause變量來這裏幹什麼?

+0

我已經在AS開始前聲明瞭@whereClause – MichaelJ

+0

我們無法確定第42行是。請參閱編輯,我添加了另一個點 – Norsk

+0

我想使用whereClause作爲過濾器,我將從前端獲取並傳遞該過濾器。有沒有更好的辦法? – MichaelJ

2

您不能只在您正在編寫的查詢中混合參數。

您需要使用動態SQL來完成此操作,這樣您就可以將整個查詢構建爲一個字符串。

像:

EXEC('select id,itemNo,tstations_id, datetimestamp from tProduction_Count ' + @whereClause) 

但是,你不能聲明光標移到動態查詢,所以一個辦法是插入執行的結果到一個臨時表,然後生成光標置於表格。

如果您可以通過接收您在常規查詢中使用的參數來完全避免動態SQL,那麼動態SQL更難以調試,並且如果您從前端接收到此消息,則可能會暴露出來到SQL注入攻擊。

相關問題