我有以下查询。
with getstock as
(
select
a.bomparent, a.bomchild, a.bomqty, a.bompos, a.baltmethod, a.bomissue
from
bom a
where
bomparent = 'QZ10-0262601' and baltmethod = '1'
union all
select
parent.bomparent, parent.bomchild, parent.bomqty, parent.bompos, parent.baltmethod, parent.bomissue
from
getstock as a
inner join
bom as parent, stock as s on parent.bomparent = a.bomchild
where
parent.baltmethod = '1' and parent.bomparent = s.stocknum
)
select *
from getstock
当我运行它时,我收到以下错误。
Msg 102,Level 15,State 1,Line 9
','附近的语法不正确。
问题出在哪里?
答案 0 :(得分:5)
您无法在JOIN
中使用多个表格。它可能在FROM
,但我不会暗示这一点。这是旧式JOIN
语法。您应该使用显式JOIN
:
with getstock as
(
select
a.bomparent, a.bomchild, a.bomqty, a.bompos, a.baltmethod, a.bomissue
from
bom a
where
bomparent = 'QZ10-0262601' and baltmethod = '1'
union all
select
parent.bomparent, parent.bomchild, parent.bomqty, parent.bompos, parent.baltmethod, parent.bomissue
from
getstock as a
inner join
bom as parent on parent.bomparent = a.bomchild
inner join
stock as s on parent.bomparent = s.stocknum
where
parent.baltmethod = '1'
)
select *
from getstock
答案 1 :(得分:1)
with getstock as
(
select a.bomparent, a.bomchild, a.bomqty, a.bompos,
a.baltmethod, a.bomissue
from bom a
where bomparent = 'QZ10-0262601' and baltmethod = '1'
union all
select parent.bomparent, parent.bomchild, parent.bomqty,
parent.bompos, parent.baltmethod, parent.bomissue
from getstock as a
inner join bom as parent
on parent.bomparent = a.bomchild
inner join stock as s
parent.bomparent = s.stocknum
where parent.baltmethod = '1'
)
select *
from getstock
答案 2 :(得分:1)
您也可以使用适当的联接重新编写查询,以使用union all,如下所示:
SELECT bomparent, bomchild, bomqty, bompos, baltmethod, bomissue
FROM bom AS a
WHERE (bomparent = 'QZ10-0262601') AND (baltmethod = '1')
union all
SELECT bom.bomparent, bom.bomchild, bom.bomqty, bom.bompos, bom.baltmethod, bom.bomissue
FROM getstock INNER JOIN
bom ON getstock.bomchild = bom.bomparent INNER JOIN
stock ON bom.bomparent = stock.stocknum
WHERE (bom.baltmethod = N'1')
答案 3 :(得分:1)
以下代码应该有效但不遵循最佳做法。始终正确使用加入条件(INNER JOIN ... ON)。
with getstock as ( select a.bomparent, a.bomchild, a.bomqty, a.bompos, a.baltmethod, a.bomissue from bom a where bomparent = 'QZ10-0262601' and baltmethod = '1' union all select parent.bomparent, parent.bomchild, parent.bomqty, parent.bompos, parent.baltmethod, parent.bomissue from getstock as a, bom as parent, stock as s where parent.bomparent = a.bomchild and parent.baltmethod = '1' and parent.bomparent = s.stocknum ) select * from getstock