SQL插入选择选择查询

时间:2017-04-10 20:30:24

标签: sql sql-server tsql

我遇到了运行插件查询的需要,这可能超出了我的专业知识。你可能会在下面看到我就像一只狗在这一点上追逐他的尾巴而且我的代码不再正确了。

问题1:它只是没有做我需要的东西而且我很难用一个查询来获取它。 问题2:似乎对BOXES表格中的每一行执行了4次。

我目前的代码:

INSERT INTO [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES_LINES] 
(
    [SALES_ORDER_NUMBER],
    [SALES_ORDER_ID],
    [SO_LINE_NUMBER],
    [SO_LINE_ID],
    [FINISHED_PART_NUMBER],
    [QUANTITY],
    [AOF_BOXES_ID]
) 
    SELECT 
        [SALES_ORDER_NUMBER],
        [SALES_ORDER_ID],
        [SO_LINE_NUMBER],
        [SO_LINE_ID],
        [FINISHED_PART_NUMBER],
        0,
        b.[ID] 
    FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_ALL_ORDER_LINES] AS aoL 
    LEFT JOIN [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES] AS b 
    ON b.[SELECTED] = 'True'
WHERE EXISTS 
(
    SELECT oL.[SO_LINE_NUMBER] FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_ORDER_OPTICS] AS oL WHERE oL.[SERIAL_NUMBER] = 'EOSBAB130004'
)

我需要INSERT INTO一行数据,其中包含来自其他几个表的数据选择。关键部分是最终的WHERE语句。我需要从与我提供的[SO_LINE_NUMBER]关联的[AOF_ORDER_OPTICS]表中获取[SERIAL_NUMBER]

感谢所有帮助。

1 个答案:

答案 0 :(得分:0)

您需要通过公钥将AOF_ALL_ORDER_LINES加入AOF_BOXES。如果没有连接它们的公共值,或者可以从另一个中间表派生的值,则无法加入表。尝试这样的事情:

INSERT INTO [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES_LINES] 
(
    [SALES_ORDER_NUMBER],
    [SALES_ORDER_ID],
    [SO_LINE_NUMBER],
    [SO_LINE_ID],
    [FINISHED_PART_NUMBER],
    [QUANTITY],
    [AOF_BOXES_ID]
) 
    SELECT 
        [SALES_ORDER_NUMBER],
        [SALES_ORDER_ID],
        [SO_LINE_NUMBER],
        [SO_LINE_ID],
        [FINISHED_PART_NUMBER],
        0,
        b.[ID] 
    FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_ALL_ORDER_LINES] AS aoL 
    LEFT JOIN [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES] AS b 
    ON b.[SELECTED] = 'True' and b.SO_Line_Id=ol.So_Line_Id
WHERE oL.[SERIAL_NUMBER] = 'EOSBAB130004'

如果没有帮助,我们可能需要有关数据的更多信息

替代方法是,您可以使用公用表表达式“伪造”中间表以连接两个表:

with CTEboL as (
select 'EOSBAB130004' AS ser,'True' AS selected

)

INSERT INTO [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES_LINES] 
(
    [SALES_ORDER_NUMBER],
    [SALES_ORDER_ID],
    [SO_LINE_NUMBER],
    [SO_LINE_ID],
    [FINISHED_PART_NUMBER],
    [QUANTITY],
    [AOF_BOXES_ID]
) 
    SELECT 
        [SALES_ORDER_NUMBER],
        [SALES_ORDER_ID],
        [SO_LINE_NUMBER],
        [SO_LINE_ID],
        [FINISHED_PART_NUMBER],
        0,
        b.[ID] 
    FROM [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_ALL_ORDER_LINES] AS aoL 
    Join CTEbol on aol.Serial_Number=CTEbol.ser
    JOIN [ROBOTICS_OPTICS_MECHUAT].[dbo].[AOF_BOXES] AS b 
    ON b.[SELECTED] = CTEbol.Selected and b.SO_Line_Id=ol.So_Line_Id