0

这是我的 SQL 查询:

SELECT 
    b.MaakArtikel, 
    b.Bewerking,
    [pp].dbo.WORKINGDAYADD('2013-06-27 00:00:00.000',0-b.Startdag_backwards) AS Startdatum, 
    i.Class_06 AS Afdeling, 
    b.Minuten*10+ISNULL(br.Tijd,0) AS Minuten, 
    1+ISNULL(br.Orders,0) AS Aantal 
FROM [pp].dbo.VW_BEWERKINGSTRUCTUUR b 
    LEFT OUTER JOIN [211].dbo.Items i 
        ON b.MaakArtikel = i.ItemCode 
    LEFT OUTER JOIN [pp].dbo.VW_BEZETTING_RAW br 
        ON [pp].dbo.WORKINGDAYADD('2013-06-27 00:00:00.000',0-b.Startdag_backwards) = br.Start 
        AND i.Class_06 = br.Afdeling 
WHERE MaakArtikel = 'HT 10.038'

查询工作正常,但速度有点慢。那是因为我的第二个OUTER JOIN. Startdatum我必须通过(在第 4 行选择)加入视图。由于它不是真正的列名,我不能直接在我的OUTER JOIN. 这意味着该功能[pp].dbo.WORKINGDAYADD()必须被触发两次(一次在我的选择中没有问题,一次在我的选择OUTER JOIN中是双重工作)。

我可以编写一个存储过程并[pp].dbo.WORKINGDAYADD()在变量中使用函数的结果,但这并不令人讨厌。有没有办法在我的OUTER JOIN表达中使用 Startdatum?或者我真的必须为此使用存储过程吗?

4

3 回答 3

1

您可以将函数移动到子查询,如下所示:

SELECT  MaakArtikel, 
        Bewerking,
        b.Startdatum, 
        i.Class_06 AS Afdeling, 
        Minuten * 10 + ISNULL(br.Tijd,0) AS Minuten, 
        1 + ISNULL(br.Orders, 0) AS Aantal 
FROM    (   SELECT  *, 
                    StartDatum = [pp].dbo.WORKINGDAYADD('2013-06-27 00:00:00.000', 0 - Startdag_backwards)
            FROM    [pp].dbo.VW_BEWERKINGSTRUCTUUR b 
        ) b
        LEFT OUTER JOIN [211].dbo.Items i 
            ON b.MaakArtikel = i.ItemCode 
        LEFT OUTER JOIN [pp].dbo.VW_BEZETTING_RAW br 
            ON b.Startdatum = br.Start 
            AND i.Class_06 = br.Afdeling 
WHERE   MaakArtikel = 'HT 10.038';

笔记

我不容忍使用SELECT *,并且在您的工作查询中,您应该只用您需要的列替换它[pp].dbo.VW_BEWERKINGSTRUCTUUR

于 2013-05-29T09:47:06.170 回答
0

如何存储你的结果

[pp].dbo.WORKINGDAYADD('2013-06-27 00:00:00.000',0-Startdag_backwards) AS Startdatum

进入 SQL 变量

DECLARE @myVariable DATETIME
SET @myVariable = [pp].dbo.WORKINGDAYADD('2013-06-27 00:00:00.000',0-Startdag_backwards)

然后在您的外部连接上执行此操作

ON @myVariable = br.Start

或者类似的东西。鲍比

于 2013-05-29T09:42:59.960 回答
0

您可以将 的输出存储[pp].dbo.WORKINGDAYADD()在变量中,然后在代码中使用该变量。(我假设函数的结果数据类型是日期时间..)

DECLARE @StartDatum datetime
SET @StartDatum = ([pp].dbo.WORKINGDAYADD('2013-06-27 00:00:00.000',0-Startdag_backwards))

SELECT 
    MaakArtikel, 
    Bewerking,
    @StartDatum, 
    i.Class_06 AS Afdeling, 
    Minuten*10+ISNULL(br.Tijd,0) AS Minuten, 
    1+ISNULL(br.Orders,0) AS Aantal 
FROM [pp].dbo.VW_BEWERKINGSTRUCTUUR b 
    LEFT OUTER JOIN [211].dbo.Items i 
        ON b.MaakArtikel = i.ItemCode 
    LEFT OUTER JOIN [pp].dbo.VW_BEZETTING_RAW br 
        ON br.Start = @StartDatum 
        AND i.Class_06 = br.Afdeling 
WHERE MaakArtikel = 'HT 10.038'
于 2013-05-29T09:44:12.123 回答