如何在exec('')中编写此查询?

时间:2013-03-04 04:58:31

标签: sql-server-2005

在这里,我试图创建一个动态查询,但它给出了错误:

CREATE PROCEDURE SP_GetProductsbySales12
@top int,
@all bit,
@orderby nvarchar(20),
@orderdir nvarchar(30) 
as
begin

declare @sql nvarchar(2000)

set @sql = ('SELECT a.skucode,a.productCode,a.productName,a.totalOrder FROM 
    ( select top ')+cast(@top as nvarchar(50))+('  tblProducts.skuCode,tblProducts.productCode, tblProducts.productName, COUNT(tblOrders_Products.delivered) as totalOrder
 FROM         tblOrders_Products INNER JOIN 
                       tblProducts ON tblOrders_Products.productID = tblProducts.productID
 WHERE tblProducts.productName is not null
 GROUP BY tblOrders_Products.delivered, tblOrders_Products.productID, tblProducts.skuCode, tblProducts.productName,tblProducts.productCode
 ORDER BY totalOrder desc,tblProducts.skuCode  ) a
 ORDER BY case when  @orderdir = ''a'' and @orderby=''skucode'' then a.skuCode  end  , 
           case when  @orderdir = ''d'' and @orderby=''skucode'' then a.skuCode  end desc,

           case when  @orderdir = ''a'' and @orderby=''qty'' then a.totalOrder end,
          case when  @orderdir = ''a'' and @orderby=''qty'' then a.skuCode  end,
           case when  @orderdir = ''d'' and @orderby=''qty'' then a.totalOrder end desc,
          case when  @orderdir = ''d'' and @orderby=''qty'' then a.skuCode  end desc')
exec (@sql)


end
GO

我收到错误

  

服务器:Msg 137,Level 15,State 2,Line 8   必须声明变量'@orderdir'。

为什么即使声明了@orderdir,我也会得到这个?

1 个答案:

答案 0 :(得分:4)

使用sp_executesql传入您的变量。

http://msdn.microsoft.com/en-us/library/ms188001.aspx

exec sp_executesql @sql,
                   N'@orderdir nvarchar(30)',
                   @orderdir=@orderdir