2014-02-05 101 views
-3

當我編譯沒有任何問題,但是當我執行這個存儲過程,我得到:附近有語法錯誤「」在SQL動態查詢

附近有語法錯誤「」

我不能爲我的生命找出其中的問題是:

DECLARE @sql nvarchar(4000) 
SET @sql = 'SELECT idea, id, posted_by 
    FROM 
    (idea,id, posted_by, ROW_NUMBER() OVER(ORDER BY ' + @sortExpression + ') as RowNum 
    FROM ideas e 
    INNER JOIN buckets d ON 
     e.bucket_id = d.id 
    WHERE e.bucket_id = ' + CONVERT(nvarchar(10), @bucketId) + ' 
) as EmpInfo 
    WHERE RowNum BETWEEN ' + CONVERT(nvarchar(10), @startRowIndex) + 
      ' AND (' + CONVERT(nvarchar(10), @startRowIndex) + ' + ' 
      + CONVERT(nvarchar(10), @maximumRows) + ') - 1' 

EXEC sp_executesql @sql 
+0

您可以輸出'@ sql'變量並在此處發佈結果。準備好的語句是正確的,但串聯的字符串可能不是。這意味着'EXEC'功能導致錯誤。 –

+7

該子查詢看起來像缺少其「SELECT」。 –

+0

使用「print(@sql)」在'EXEC' –

回答

1

你在你的內部查詢的開始需要一個SELECT

DECLARE @sql nvarchar(4000) 
SET @sql = 'SELECT idea, id, posted_by 
    FROM 
(**SELECT** idea,id, posted_by, ROW_NUMBER() OVER(ORDER BY ' + @sortExpression + ') as RowNum 
FROM ideas e 
INNER JOIN buckets d ON 
    e.bucket_id = d.id 
WHERE e.bucket_id = ' + CONVERT(nvarchar(10), @bucketId) + ' 
) as EmpInfo 
WHERE RowNum BETWEEN ' + CONVERT(nvarchar(10), @startRowIndex) + 
     ' AND (' + CONVERT(nvarchar(10), @startRowIndex) + ' + ' 
     + CONVERT(nvarchar(10), @maximumRows) + ') - 1' 

EXEC sp_executesql @sql 

希望能正確顯示。我試圖大膽工作選擇

0

你缺少內部select

DECLARE @sql nvarchar(4000) 
SET @sql = 'SELECT idea, id, posted_by 
    FROM 
    (**SELECT** idea,id, posted_by, ROW_NUMBER() OVER(ORDER BY ' + @sortExpression + ') as RowNum 
    FROM ideas e 
    INNER JOIN buckets d ON 
     e.bucket_id = d.id 
    WHERE e.bucket_id = ' + CONVERT(nvarchar(10), @bucketId) + ' 
) as EmpInfo 
    WHERE RowNum BETWEEN ' + CONVERT(nvarchar(10), @startRowIndex) + 
      ' AND (' + CONVERT(nvarchar(10), @startRowIndex) + ' + ' 
      + CONVERT(nvarchar(10), @maximumRows) + ') - 1' 

EXEC sp_executesql @sql 
3

你不應該連接所有這些東西變成動態SQL。事實上,你應該嘗試使用ORDER BY表達式而不用引入動態SQL,但是我知道當用戶可以選擇多列,不同數據類型和兩個方向時(I discussed this problem here),所以請傳入另一個參數安全:

DECLARE @sql nvarchar(4000); -- always use semi-colons 

DECLARE @r INT; 

SET @r = @startRowIndex + @maximumRows - 1; 

SET @sql = 'SELECT idea, id, posted_by 
FROM 
(
    SELECT -- this was your actual problem 
    idea,id, posted_by, -- you should prefix these with the alias 
    ROW_NUMBER() OVER (ORDER BY ' + @sortExpression + ') as RowNum 
    FROM dbo.ideas e -- always use schema prefix 
    INNER JOIN dbo.buckets d ON 
    e.bucket_id = d.id 
    WHERE e.bucket_id = @bucketId 
) as EmpInfo 
WHERE RowNum BETWEEN @startRowIndex AND @r;'; 

EXEC sp_executesql @sql, N'@startRowIndex INT, @bucketId INT, @r INT', 
    @startRowIndex, @bucketId, @r; 

對於我的一些評論:

此外,如果您使用SQL Server 2012,則應該使用OFFSET/FETCH