我的数据库出现此问题。我的代码是:
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项必须出现在选择列表中。
请帮帮我。
答案 0 :(得分: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'
答案 1 :(得分: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
有点难以弄清楚。