选择语句时出现动态SQL字符串错误

时间:2015-01-26 18:30:59

标签: sql stored-procedures dynamic-sql

我有一个动态的sql语句,我相信它会解决我的问题,当我创建过程时,select语句有''引用''的问题。

这是我的程序。

    CREATE PROCEDURE GetPanelData(@FirstYear int = null, @SecondYear int = null, @ThirdYear int = null, @CompanySelected int = null)
AS
SET NOCOUNT ON;
DECLARE @SQL NVARCHAR(4000);
DECLARE @ParameterDefinition NVARCHAR(4000);

SELECT @ParameterDefinition = '@Year1 int,
                               @Year2 int,
                               @Year3 int,
                               @companyID int';

SELECT @SQL = N'
    SELECT FirstColumn.Type, 
            FirstColumn.YearPanelCount,
            SecondColumn.YearPanelCount

    FROM
     (SELECT ''Quote'' AS Type, sum(mdl.Panel) AS YearPanelCount
     FROM Model mdl, Quote QT, Quote_Line_Items QLT, Products Prd
     WHERE QT.QuoteID = QLT.QuoteID AND
      QLT.ProductID = Prd.ProductID AND
      Prd.ModelID = mdl.ModelID AND
      DATEPART(YYYY, QT.Quote_Date) = @Year1 AND
      Prd.CompanyID = @companyID) AS FirstColumn
';

IF @SecondYear IS NOT NULL
    SELECT @SQL = @SQL + N'
    inner join(
    SELECT ''Quote'' AS Type, sum(mdl.Panel) AS YearPanelCount
    FROM Model mdl, Quote QT, Quote_Line_Items QLT, Products Prd
    WHERE QT.QuoteID = QLT.QuoteID AND
      QLT.ProductID = Prd.ProductID AND
      Prd.ModelID = mdl.ModelID AND
      DATEPART(YYYY, QT.Quote_Date) = @Year2 AND
      Prd.CompanyID = @companyID) AS SecondColumn
    on FirstColumn.Type = SecondColumn.Type
';

IF @ThirdYear IS NOT NULL
    SELECT @SQL = @SQL + N'
    inner join(
    (SELECT ''Quote'' AS Type, sum(mdl.Panel) AS YearPanelCount
    FROM Model mdl, Quote QT, Quote_Line_Items QLT, Products Prd
    WHERE QT.QuoteID = QLT.QuoteID AND
      QLT.ProductID = Prd.ProductID AND
      Prd.ModelID = mdl.ModelID AND
      DATEPART(YYYY, QT.Quote_Date) = @Year3 AND
      Prd.CompanyID = @companyID)) AS ThirdColumn
    on FirstColumn.Type = ThirdColumn.Type
    ';

EXEC sp_executeSQL  @SQL, 
    @ParameterDefinition, 
    @Year1 = @FirstYear, 
    @Year2 = @SecondYear, 
    @Year3 = @ThirdYear,
    @CompanyID = @CompanySelected;
GO

EXEC GetPanelData @FirstYear = 2012, @SecondYear = 2013, @CompanySelected = '1';

有人知道我运行它时为什么会出现此错误。 Msg 102,Level 15,State 1,Line 27 'Quote'附近的语法不正确。

当我运行查询SELECT'Quote'时,sum(mdl.Panel)它可以工作,但出于某种原因,在这种情况下它不能。

1 个答案:

答案 0 :(得分:0)

我看到两个问题。第一个是整个查询的结束引用取决于@ThirdYear参数,该参数在执行时为空,为您留下一个未闭合的括号。第一个开括号似乎没必要,所以我会改变

SELECT @SQL = N'
(SELECT FirstColumn.Type,...

SELECT @SQL = N'
SELECT FirstColumn.Type,...

如果您希望将查询包含在括号中,则应在参数化集之后将闭括号移动到最终set

SET @SQL = @SQL + ')'

我看到的第二个问题,我认为在修复第一个问题后会抛出另一个错误,就是您正在尝试加入不存在的列名Quote。也许您打算加入列名Type