Sql server问题ORDER BY子句在视图中无效

时间:2013-12-09 14:47:02

标签: sql-server-2005

在这里,我将发布完整的存储过程代码,然后我将选择出错的区域。

ALTER PROC [dbo].[WarrantyTrends]
(
    @StartYr AS INT,
    @EndYr  AS INT  
)
AS
    DECLARE @query varchar(max)
    DECLARE @years varchar(max), @yearsColumns varchar(max)

    SELECT 1 mID, 'January' as month  into #tempMonths   UNION ALL 
    SELECT 2,'February' as month     UNION ALL 
    SELECT 3,'March' as month     UNION ALL 
    SELECT 4,'April' as month     UNION ALL 
    SELECT 5,'May' as month     UNION ALL 
    SELECT 6,'June' as month     UNION ALL 
    SELECT 7,'July' as month     UNION ALL 
    SELECT 8,'August' as month     UNION ALL 
    SELECT 9,'September' as month     UNION ALL 
    SELECT 10,'October' as month    UNION ALL 
    SELECT 11,'November' as month    UNION ALL 
    SELECT 12,'December' as month  

    SELECT @years=COALESCE(@years+',','')   +'['+ cast(years as varchar(4))+']',
    @yearsColumns=COALESCE(@yearsColumns+',','')   +'isnull(['+ cast(years as varchar(4))+'],0) 
    as ['+cast(years as varchar(4))+']'
    from  (select distinct YEAR(CurDate) years from EOD_Main
    WHERE YEAR(CurDate)>=@StartYr AND YEAR(CurDate)<=@EndYr 
    ) as x

    SET @query = 'Select months,'+@yearsColumns+' from (
    select distinct mID, YEAR(CurDate)  years,[MONTH] months,  
    isnull(Warranty_Info,0) as Warranty_Info  from EOD_Main
          right join #tempMonths on datename(month,CurDate ) =[month] 
    ) as xx
    PIVOT 
    (
    SUM(xx.Warranty_Info) FOR years IN ('+@years+')
    )
    as pvt ORDER BY mID'
    PRINT @query
    --EXEC(@query)

   drop table #tempMonths   

请参阅此代码

SELECT 
    @years = COALESCE(@years+',','')   +'['+ cast(years as varchar(4))+']',
    @yearsColumns = COALESCE(@yearsColumns+',','')   +'isnull(['+ cast(years as varchar(4))+'], 0) as ['+cast(years as varchar(4))+']'
FROM 
    (SELECT distinct YEAR(CurDate) years 
     FROM EOD_Main
     WHERE YEAR(CurDate) >= @StartYr AND YEAR(CurDate) <= @EndYr) as x

这个最里面的区域

 (SELECT distinct YEAR(CurDate) years 
  FROM EOD_Main
  WHERE YEAR(CurDate) >= @StartYr AND YEAR(CurDate) <= @EndYr) as x**

我无法明智地订购这一年而不是错误。

在这个领域,我想要产生一年的提升......所以指导我能做什么。感谢

1 个答案:

答案 0 :(得分:1)

排序与观点无关。你不会自动获得正确的记录。你需要在你想要的所有sql代码中有一个订单。

Order by year(curDate)