SQL动态查询中','附近的语法不正确

时间:2014-02-05 17:37:40

标签: sql sql-server dynamic

当我编译时没有问题,但是当我执行这个存储过程时,我得到:

  

','

附近的语法不正确

我不能为我的生活找出问题所在:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

希望正确显示。我试图大胆工作SELECT

答案 2 :(得分: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