在这里,我试图创建一个动态查询,但它给出了错误:
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
我收到的错误是
服务器:消息 137,级别 15,状态 2,第 8 行 必须声明变量“@orderdir”。
为什么即使声明了@orderdir,我也会得到这个?