I want to convert a stored procedure to a SQL query.
Here is the stored procedure in simple format:
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
To convert this stored procedure into a SQL query, can I replace all the #raw_data
in the second SELECT
statement with:
SELECT table1.*
FROM table_1 WITH (NOLOCK)
WHERE (a lot of conditions and filtering follows)
I would like to know if there is a better way to do it.
So you turned it into...
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
But you should keep going. The correlated subquery is not needed in this case. It doesn't appear to add any value. It makes the query more complicated. It also slows it down since the subquery must be run once for every row in the outer query. To take advantage of SQL Server's ability to join sets of data en masse...
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
Assuming you're always joining table_1 to table_1 by using the same column on both sides of the join, as in your code) you may be able to simplify further. Be careful here. I assume that xid is unique or is included in the join between a
and aa
. If it is not, you'll want to stop here.
So, if you can simplify further, the next step is...
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
...and can be simplified to...
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)
It looks like there may be considerably more complexity that you didn't share (the three dots of uncertainty).
WHERE aa.id1 = a.id1
AND aa.id2 = a.id2
...
Your mileage may vary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.