2012-04-27 71 views
0

我必須使用動態SQL解決方案創建存儲過程,因爲如果條件需要包含多個嵌套。當我在查詢分析器中運行代碼時收到以下錯誤。我的存儲過程有什麼問題

Msg 156, Level 15, State 1, Line 13 
Incorrect syntax near the keyword 'Procedure'. 

我想創建的方法如下:

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
IF EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[sp_Payments]') 
AND type in (N'P', N'PC')) 
Drop procedure sp_Payments 
BEGIN 
DECLARE @SQL varchar(max), 
    @categoryID smallint, 
    @startDate datetime, 
    @stopDate datetime, 
    @debtCode tinyint, 
    @izEscrow tinyint 


Create Procedure sp_Payments 
    (@categoryID smallint, 
    @startDate datetime, 
    @stopDate datetime, 
    @debtCode tinyint, 
    @izEscrow tinyint 
    ) 
AS 
BEGIN 
Declare @Payments table( 
     paydate datetime, 
     principaldue float, 
     interestdue float, 
     debtid int, 
     debtname varchar(50), 
     debtnumber varchar(10), 
     fsrc varchar(40), 
     category varchar(40), 
     PayMonth tinyint, 
     PayYear int 
) 
SET @SQL = ' 
insert into @Payments 
     select dtl.paydate, 
      dtl.principaldue, 
      dtl.interestdue, 
      dtl.debtid, 
      dmf.debtname, 
      dmf.debtnumber, 
      fsrc.fsrc, 
      app.category, 
      month(dtl.paydate) as PayMonth, 
      case 
       when month(PayDate) <= 6 then year(PayDate) 
       else year(PayDate)+1 
      end "PayYear" 
      from debtdetail dtl 
      inner join masterfile dmf 
      on dtl.debtid = dmf.debtid 
      inner join categories app 
      on dmf.categoryid = app.categoryid 
      left outer join fsrc 
      on dmf.fsrcid = fsrc.fsrcid 
      left outer join debtissues di 
      on dmf.issueid = di.issueid 
       where dtl.debtid in 
      (select debtid from masterfile 
       where categoryid = @categoryID ' 

     IF @debtCode > 0  
      SET @SQL = @SQL + ' 
       AND codeid = @debtCode 
       ' 
      SET @SQL = @SQL + ' 
       ) 
       AND di.iscontingent = 0 
       ' 
      IF @stopDate = '' 
       SET @SQL = @SQL + ' 
        and dtl.paydate >= @startDate 
       ' 
      ELSE 
       SET @SQL = @SQL + ' 
        and dtl.paydate between 
        @startDate AND @stopDate 
       ' 
      IF @izEscrow = 0 
       SET @SQL = @SQL + ' 
        and dtl.isescrow = 0 
       ' 
      SET @SQL = @SQL + ' 
      and (principaldue + interestdue) > 0 and dtl.active = 1 
        order by dtl.Paydate, dmf.DebtNumber ' 
EXEC @SQL 
END 

    SELECT * from @Payments 

RETURN 




END 

任何幫助,將不勝感激。在此先感謝

+2

您的批次之間需要'GO's這裏。 – JNK 2012-04-27 19:11:07

+0

還有其他問題。這是一個非常倒退的設計。爲什麼要聲明所有的變量,然後創建具有相同名稱的參數? – JNK 2012-04-27 19:12:35

+1

查詢分析器?你的意思是管理工作室?如果您針對SQL Server 2000運行此代碼,則有很多事情會阻止其運行。請指定您正在使用的SQL Server版本。 [tag:sql-server]不夠具體。 – 2012-04-27 19:41:21

回答

-2

擺脫動態SQL,並且這樣做:

AND (@debtCode = 0 OR codeId = @debtCode) 
... and so on 
+3

可能不適合專業開發人員的站點語言。 – JNK 2012-04-27 19:13:15