我已经创建了一个用于填充下拉列表的存储过程。但是order by子句对我的过程不起作用。
ALTER PROCEDURE proc
-- Add the parameters for the stored procedure here
@compID bigint,
@after datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
CREATE TABLE #tmpAuc ( ProjectID BIGINT, Title VARCHAR(256))
INSERT INTO #tmpAuc
SELECT SA.ID ProjectID, SA.Title
FROM [dbo].[Sessions] S
INNER JOIN Auc SA ON S.AucID = SA.ID
WHERE S.Session < 3 AND SA.Status > 0 AND SA.CompanyID = @companyID AND S.LiveBeginDate > @after
ORDER BY LiveBeginDate
SELECT DISTINCT * FROM #tmpAuc
END
我想按LiveBehinDate的降序顺序
答案 0 :(得分:2)
在临时表中以及临时表结果LiveBeginDate
中包含ORDER BY LiveBeginDate
CREATE TABLE #tmpAuctions (ProjectID BIGINT, Title VARCHAR(256), LiveBeginDate DATETIME)
INSERT INTO #tmpAuctions (ProjectID, Title, LiveBeginDate)
SELECT SA.ID AS ProjectID, SA.Title, S.LiveBeginDate
FROM [dbo].[Sessions] S
INNER JOIN [Spectrum_Auctions].[dbo].[Auctions] SA ON S.AuctionID = SA.ID
WHERE S.SessionState < 3 AND SA.Status > 0 AND SA.CompanyID = @companyID AND S.LiveBeginDate > @after
SELECT DISTINCT *
FROM #tmpAuctions
ORDER BY LiveBeginDate
或避免使用临时表,并直接在过程内使用带有JOIN的SELECT:
SELECT SA.ID AS ProjectID, SA.Title
FROM [dbo].[Sessions] S
INNER JOIN [Spectrum_Auctions].[dbo].[Auctions] SA ON S.AuctionID = SA.ID
WHERE S.SessionState < 3 AND SA.Status > 0 AND SA.CompanyID = @companyID AND S.LiveBeginDate > @after
ORDER BY S.LiveBeginDate
答案 1 :(得分:1)
这是因为在写入驻留在temp dB中的temp表时,数据是有序的。永远不能保证从temp dB读取数据。因此,当您从临时表中选择星号时,您将获得。 摆脱临时表并直接进行选择。这也将更快,更高效。如果您的proc变得更加复杂,请使用CTE而不是临时表,因为它们在所有情况下都更易于概念化且运行速度更快。