CREATE TABLE `cc_comment_master` (
`ID` int(11) DEFAULT NULL,
`DRAFT_SALESDOC_HEADER_ID` int(11) DEFAULT NULL,
`PRODUCT_ID` int(11) DEFAULT NULL,
`PRODUCT_NUMBER` varchar(50) DEFAULT NULL,
`COMMENT_DESC` varchar(100) DEFAULT NULL,
`COMMENT_BY` varchar(50) DEFAULT NULL,
`COMMENT_ON` datetime DEFAULT NULL,
`MODIFIED_BY` varchar(100) DEFAULT NULL,
`MODIFIED_ON` datetime DEFAULT NULL,
`CREATED_BY` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `cc_comment_master`(`ID`,`DRAFT_SALESDOC_HEADER_ID`,`PRODUCT_ID`,`PRODUCT_NUMBER`,`COMMENT_DESC`,`COMMENT_BY`,`COMMENT_ON`,`MODIFIED_BY`,`MODIFIED_ON`,`CREATED_BY`)
values (1,1,1,'abc','first','test','2016-01-12 10:43:48','test',NULL,'test'),(2,2,2,'def','second','test','2016-01-12 10:43:53','test',NULL,'test'),(3,3,3,'xyz','third','test','2016-01-12 10:43:56','test',NULL,'test'),(4,4,4,'pqr','four','test','2016-01-12 10:44:33','test',NULL,'test');
查询:
declare @comments varchar(max)
set @comments = ''
Select
@comments = @comments +''+ COMMENT_DESC+'-COMMENT_SEPERATOR-'
from
CC_COMMENT_MASTER c
where
c.DRAFT_SALESDOC_HEADER_ID = 1
and PRODUCT_NUMBER = 'abc'
order by
c.COMMENT_ON desc --order by not working
select @comments;
我想选择一个字符串中附加的所有COMMENT_DESC,按COMMENT_ON降序排列。
没有order by子句,我在一个字符串中以asc顺序获取所有COMMENT_DESC。当我尝试通过COMMENT_ON desc订购时,它无法正常工作。
输出:
first-COMMENT_SEPERATOR-
预期产出:
first-COMMENT_SEPERATOR-second-COMMENT_SEPERATOR-third--COMMENT_SEPERATOR-
错误:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
答案 0 :(得分:0)
试试这个
declare @comments varchar(max)
set @comments = ''
Select
@comments = @comments +''+ COMMENT_DESC+'-COMMENT_SEPERATOR-'
from
(select top 100 percent * from CC_COMMENT_MASTER c order by COMMENT_ON desc) as t
select @comments;
答案 1 :(得分:0)
他们将不会在where子句中为该条件订购多条记录。 只要删除条件,我认为它会起作用
declare @comments varchar(max)
set @comments = ''
Select
@comments = @comments +''+ COMMENT_DESC+'-COMMENT_SEPERATOR-'
from
CC_COMMENT_MASTER c
order by
c.COMMENT_ON desc
然后移除那个desc,它会向后输出。
答案 2 :(得分:0)
以下查询对我有用。
DECLARE @comments nvarchar(max);
SET @comments='';
SELECT @comments= @comments +''+ TEMP.COMMENT_DESC +'COMMENT_SEPERATOR'
FROM
(SELECT *, ROW_NUMBER() OVER (ORDER BY c.COMMENT_ON) AS RowNum FROM CC_COMMENT_MASTER c
WHERE c.DRAFT_SALESDOC_HEADER_ID=1 AND c.PRODUCT_NUMBER='abc' ) AS TEMP
ORDER BY TEMP.RowNum;
SELECT @comments;