我正在处理的是正确返回的查询。
DECLARE @theItewId VARCHAR(100) = (SELECT item_id
FROM ndc_attr
WHERE attr_val = '00310072010');
SELECT nr.item_id,
nr.field_id,
nr.attr_val,
nr.upd_dtt,
nr.upd_usr,
nr.item_id,
1 AS counting,
nr.field_id
FROM ndc_attr nr
WHERE item_id = @theItewId
AND field_id IN ( 69, 144, 150, 148, 170 )
UNION ALL
SELECT TOP 1 @theItewId AS item_id,
418 AS field_id,
nr.contract_num_val AS attr_val,
CURRENT_TIMESTAMP AS upd_dtt,
'-1' AS upd_usr,
'-1' AS item_id,
'-1' AS counting,
'-1' AS field_id
FROM contract_ndc_brg nr
WHERE ndc_id = '00310072010'
ORDER BY upd_dtt DESC
但是当我尝试添加另一个UNION ALL时,我收到了一个错误,并且不明白为什么。
DECLARE @theItewId VARCHAR(100) = (SELECT item_id
FROM ndc_attr
WHERE attr_val = '00310072010');
SELECT nr.item_id,
nr.field_id,
nr.attr_val,
nr.upd_dtt,
nr.upd_usr,
nr.item_id,
1 AS counting,
nr.field_id
FROM ndc_attr nr
WHERE item_id = @theItewId
AND field_id IN ( 69, 144, 150, 148, 170 )
UNION ALL
SELECT TOP 1 @theItewId AS item_id,
418 AS field_id,
nr.contract_num_val AS attr_val,
CURRENT_TIMESTAMP AS upd_dtt,
'-1' AS upd_usr,
'-1' AS item_id,
'-1' AS counting,
'-1' AS field_id
FROM contract_ndc_brg nr
WHERE ndc_id = '00310072010'
ORDER BY upd_dtt DESC
UNION ALL
SELECT TOP 1 @theItewId AS item_id,
981 AS field_id,
nr.quote_price AS attr_val,
CURRENT_TIMESTAMP AS upd_dtt,
'-1' AS upd_usr,
'-1' AS item_id,
'-1' AS counting,
'-1' AS field_id
FROM contract_ndc_brg nr
WHERE ndc_id = '00310072010'
ORDER BY upd_dtt DESC
我做错了什么以及如何解决?
编辑:
消息156,级别15,状态1,程序USP_ENTY_ATTR_GET_BY_ATTR_VALS,第151行
关键字' UNION'附近的语法不正确。
答案 0 :(得分:3)
我认为问题是你不能在你的一个UNIONS中进行ORDER BY。您可以执行此操作,但需要将语句封装在子查询中:
SELECT * FROM
(SELECT nr.item_id,
nr.field_id,
nr.attr_val,
nr.upd_dtt,
nr.upd_usr,
nr.item_id,
1 AS counting,
nr.field_id
FROM ndc_attr nr
WHERE item_id = @theItewId
AND field_id IN ( 69, 144, 150, 148, 170 ) ) as t1
UNION ALL
SELECT * FROM
(SELECT TOP 1 @theItewId AS item_id,
418 AS field_id,
nr.contract_num_val AS attr_val,
CURRENT_TIMESTAMP AS upd_dtt,
'-1' AS upd_usr,
'-1' AS item_id,
'-1' AS counting,
'-1' AS field_id
FROM contract_ndc_brg nr
WHERE ndc_id = '00310072010'
ORDER BY upd_dtt DESC ) as t2
UNION ALL
SELECT * FROM
(SELECT TOP 1 @theItewId AS item_id,
981 AS field_id,
nr.quote_price AS attr_val,
CURRENT_TIMESTAMP AS upd_dtt,
'-1' AS upd_usr,
'-1' AS item_id,
'-1' AS counting,
'-1' AS field_id
FROM contract_ndc_brg nr
WHERE ndc_id = '00310072010'
ORDER BY upd_dtt DESC ) as t3
答案 1 :(得分:2)
ORDER BY必须只进行一次并位于查询的底部。你重复了这一行:
ORDER BY upd_dtt DESC
导致错误