我的存储过程有什么问题

时间:2012-04-27 19:06:03

标签: sql-server stored-procedures

我必须使用动态SQL解决方案创建存储过程,因为如果条件,我需要包含几个嵌套。我在Query Analyzeer中运行代码时收到以下错误。

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 

任何帮助将不胜感激。提前致谢

1 个答案:

答案 0 :(得分:-2)

摆脱那个动态的sql,并执行以下操作:

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