繁体   English   中英

将 SQL 服务器存储过程转换为查询

[英]Conversion of SQL Server stored procedure to a query

我想将存储过程转换为 SQL 查询。

这是简单格式的存储过程:

SELECT
    table1.* 
INTO 
    #raw_data
FROM 
    table_1 WITH (NOLOCK)
WHERE 
    (a lot of conditions and filtering follows)

SELECT
    xyz,
    pqr,
    (SELECT (something)
     FROM #raw_data aa
     WHERE aa.id1 = a.id1
       AND aa.id2 = a.id2
       ...)
INTO 
    #temp_data
FROM 
    #raw_data a
JOIN 
    table_2 b WITH (NOLOCK) ON a.xid = b.xid

要将此存储过程转换为 SQL 查询,我可以将第二个SELECT语句中的所有#raw_data替换为:

SELECT table1.*
FROM table_1 WITH (NOLOCK)
WHERE (a lot of conditions and filtering follows)

我想知道是否有更好的方法来做到这一点。

所以你把它变成了...

SELECT xyz
, pqr
, (
    SELECT (something)
    FROM (
    SELECT table_1.*
        FROM table_1 WITH (NOLOCK)
        WHERE (a lot of conditions and filtering follows)
    ) aa
    WHERE aa.id1 = a.id1
    AND aa.id2 = a.id2
    ...
)

INTO #temp_data

FROM (
    SELECT table_1.*
    FROM table_1 WITH (NOLOCK)
    WHERE (a lot of conditions and filtering follows)
  ) a
  inner JOIN table_2 b WITH (NOLOCK) ON a.xid = b.xid

但你应该继续前进。 在这种情况下,不需要相关子查询。 它似乎没有增加任何价值。 它使查询更加复杂。 它也会减慢它的速度,因为子查询必须为外部查询中的每一行运行一次。 为了利用 SQL 服务器的能力来加入大量数据集...

SELECT xyz
, pqr
, aa.something

INTO #temp_data

FROM (
    SELECT table_1.*
    FROM table_1 WITH (NOLOCK)
    WHERE (a lot of conditions and filtering follows)
  ) a
  inner join (
    SELECT table_1.*
    FROM table_1 WITH (NOLOCK)
    WHERE (a lot of conditions and filtering follows)
  ) aa on aa.id1 = a.id1
      and aa.id2 = a.id2
      ...
  inner JOIN table_2 b WITH (NOLOCK) ON a.xid = b.xid

假设您总是通过在连接的两侧使用相同的列将 table_1 连接到 table_1,如您的代码中一样)您可以进一步简化。 这里要小心。 我假设 xid 是唯一的,或者包含在aaa之间的连接中。 如果不是,你会想在这里停下来。

所以,如果你可以进一步简化,下一步是......

SELECT xyz
, pqr
, a.something

INTO #temp_data

FROM (
    SELECT table_1.*
    FROM table_1 WITH (NOLOCK)
    WHERE (a lot of conditions and filtering follows)
  ) a
  inner JOIN table_2 b WITH (NOLOCK) ON a.xid = b.xid

...并且可以简化为...

SELECT xyz
, pqr
, a.something

INTO #temp_data

FROM table_1 a WITH (NOLOCK)
  inner JOIN table_2 b WITH (NOLOCK) ON a.xid = b.xid

WHERE (a lot of conditions and filtering follows)

看起来您可能没有分享更多的复杂性(不确定性的三个点)。

WHERE aa.id1 = a.id1
  AND aa.id2 = a.id2
  ...

你的旅费可能会改变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM