我麻煩了basical存儲過程,可惜我不是一個SQL專家,我所要做的是排序2個參數,@OrderBy
和@SortOrder
提供結果,但結果進行排序只有子查詢的結果。 例如:ORDER BY和子查詢
exec [dbo].[GetTest2] @Page=0,@Limit=150,@OrderBy=N'NetworkName',@SortOrder=N'asc'
它能正常工作,但
exec [dbo].[GetTest2] @Page=0,@Limit=15,@OrderBy=N'NetworkName',@SortOrder=N'asc'
不工作,因爲子查詢不返回所有記錄。
我怎麼樣在整個記錄?
USE [MyContext]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter PROCEDURE [dbo].[GetTest2]
@Page int = 0,
@Limit int = 10,
@OrderBy nvarchar(50) = 'OfferId',
@Name nvarchar(100) = NULL,
@SortOrder nvarchar(50) = 'asc'
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY @OrderBy) AS ROWNUMBER,
COUNT(*) OVER() AS [Total_Rows],
a.Name AS NetworkName,
o.*
FROM offers AS o
left outer join AffiliateNetworks AS a ON o.NetworkId = a.Id
WHERE (@Name IS NULL OR o.Name LIKE '%' + @Name + '%')) AS Paged
WHERE
Paged.ROWNUMBER > @Limit * @Page AND
Paged.ROWNUMBER <= (@Limit * @Page) + @Limit
order by
case
when @SortOrder <> 'asc' then NULL
when @OrderBy = 'Name' then Name
end ASC,
case
when @SortOrder <> 'asc' then NULL
when @OrderBy = 'NetworkName' then NetworkName
end ASC,
case
when @SortOrder <> 'desc' then NULL
when @OrderBy = 'Name' then Name
end DESC,
case
when @SortOrder <> 'desc' then NULL
when @OrderBy = 'NetworkName' then NetworkName
end DESC
END
SQL不支持此構造。 使用存儲過程中,SQL方言是非常重要的。您使用哪種SQL語言?甲骨文? DB2? SQLServer的? Postgres的?等 –
我使用MS SQLSERVER,這是支持這一說法 – InferOn