1

我有一个存储过程如下:

    ALTER PROCEDURE [dbo].[GetProjectPaymentSchedules]
    @StartDate datetime
    AS
    BEGIN
        IF @StartDate IS NULL 
        BEGIN
            SET @StartDate = DateAdd(YY, -100, GetDate())
        END
        -- create our variables
        DECLARE 
        @query VARCHAR(max),
        @years VARCHAR(2000)

        SELECT  @years = STUFF((SELECT ISNULL(
                                         (SELECT * 
                                          FROM  
                                          (SELECT DISTINCT '],[' +  ltrim(Cast(PaymentDueDate as varchar(50))) As TheDate
                                           FROM    PaymentSchedule
                                           WHERE PaymentDueDate > @StartDate
                                           Union all
                                           Select DISTINCT '],[' + ltrim(Cast(DateIncurred as varchar(50))) As TheDate
                                           FROM Expense
                                           WHERE  DateIncurred > @StartDate
                                           ) Sub 
                                         ORDER BY ('],[' + ltrim(Cast(TheDate as varchar(50))))
                                         FOR XML PATH('')), 0)),1, 2, '') + ']'
    SET @query =

    'SELECT * 
    FROM

(
    (select p.Project_Desc, s.Scope_ID, ps.PaymentDueDate, ps.PaymentAmount
    from Project p
    join dbo.Scope s
    ON  s.Project_ID = p.Project_Id
    join dbo.PaymentSchedule ps
    ON ps.Scope_ID = s.Scope_ID)
    UNION ALL
    (select  ec.CategoryDesc AS Category, s.Scope_ID AS Scope, e.DateIncurred, e.ExpAmount
    from Expense e
    join dbo.ExpenseCategory ec
    on e.ExpCategory = ec.CategoryId
    join Scope s
    on (e.ScopeId = s.Scope_ID or e.ScopeId IS Null) )

)t

PIVOT (SUM(PaymentAmount) FOR PaymentDueDate

IN ('+@years+')) AS pvt
order by pvt.Scope_ID'



EXECUTE (@query)
    END

创建/更改没有问题,但是当我尝试按如下方式执行它时:

    exec dbo.AMEP_GetProjectPaymentSchedules '07-16-2012'
    exec dbo.AMEP_GetProjectPaymentSchedules NULL

两者都导致以下结果:

消息 102,级别 15,状态 1,第 24 行
'>' 附近的语法不正确。
消息 102,级别 15,状态 1,第 24 行
'>' 附近的语法不正确。

我似乎无法弄清楚是什么引发了错误

任何帮助表示赞赏

4

0 回答 0