0

我的数据库有这个问题。我的代码是:

 CREATE PROCEDURE [dbo].[test1]
    @den nchar(14) = ''         
 AS
 BEGIN  
   SET NOCOUNT ON;

   DECLARE @SQL AS varchar(3000) = ''   
   DECLARE @WHERE1 AS varchar(1000) = ''    
   DECLARE @ORDERBY1 AS varchar(1000) = ''

   SET @WHERE1 = @WHERE1 + ' WHERE [dbo].table2.sag=1 '

   IF (@den != '')      
      SET @WHERE1 = @WHERE1 + ' AND RIGHT(''0000000000''+CONVERT(VARCHAR(10),[dbo].table1_den_id1),10) +RIGHT(''0000''+CONVERT(VARCHAR(4),[dbo].table1_den_id2),4) = ''' + RIGHT('00000000000000'+RTRIM(@den),14) + ''''

   SET @ORDERBY1 = @ORDERBY1 + 'GROUP BY [dbo].table2.item_barcord      
ORDER BY LEFT([dbo].table2.item_barcord,13) ASC'

   SET @SQL = @SQL + '      
          SELECT            
          DISTINCT          
          ''JAN'' + LEFT([dbo].table2.item_barcord,13) AS ''code'',             
          LEFT(MIN([dbo].table2.item_name),15) AS ''name''      
          FROM [dbo].table1         
          INNER JOIN [dbo].table2 ON [dbo].table1.id = [dbo].table2.id          '           + @WHERE1       
          + @ORDERBY1

   DECLARE @RET AS numeric(3,0) = 0

   EXEC(@SQL)   
   SET @RET = @@ROWCOUNT

   RETURN @RET
END

但是我收到此错误:

如果指定了 SELECT DISTINCT,则 ORDER BY 项目必须出现在选择列表中。

请帮我。

4

2 回答 2

1

尝试更改此行:

SET @ORDERBY1 = @ORDERBY1 + 'GROUP BY [dbo].table2.item_barcord     
ORDER BY LEFT([dbo].table2.item_barcord,13) ASC'

至 :

SET @ORDERBY1 = @ORDERBY1 + 'GROUP BY [dbo].table2.item_barcord     
ORDER BY LEFT([dbo].table2.item_barcord,13), 2 ASC'

更多:SELECT DISTINCT 和 ORDER BY

于 2013-03-05T03:08:49.310 回答
1

我认为您应该更改查询,以便不需要select distinct

      SELECT ''JAN'' + LEFT([dbo].table2.item_barcord,13) AS ''code'',  
      . . . 
      group by LEFT([dbo].table2.item_barcord,13)

然后order by将正常工作。作为一个额外的好处,查询将更有意义——select distinct在聚合中有点难以弄清楚。

于 2013-03-05T03:11:28.093 回答