Andrew
Andrew

Reputation: 99

How to combine 2 SQL queries

We have 2 SQL queries we use to look up a database lock from a user login, as sometimes we need to unlock it manually. In short, we run the following query, which will return a few results:

SELECT DISTINCT request_session_id
FROM [view_name]
WHERE [condition1] AND [condition2]

We then take the results one at a time, and run the following query (after updating the @request_session_id variable) until we find the line that shows the correct username in the hostname column of the results (the spid values will correspond to the request_session_id's):

DECLARE @request_session_id int;
SET @request_session_id = 107;

SELECT spid, status, hostname
FROM [view_name]
WHERE spid = @request_session_id

What I would like to accomplish (if possible), is to combine these 2 queries so it will find the request_session_id's, and then automatically runs the second query, showing a results line for each ID found by the first query. I'm pretty new to SQL, but I'm familiar with Powershell, so in powershell I would simply save the results from query 1 to a variable, and then use foreach to cycle those results through query 2. I'm just not sure how I would get to the same end result with SQL.

Thanks in advance for the help.

Andrew

Upvotes: 1

Views: 58

Answers (4)

ravioli
ravioli

Reputation: 3823

Just use an IN clause to filter the spid values that you want:

SELECT spid, status, hostname
FROM [view_name]
WHERE spid IN (
  SELECT request_session_id
  FROM [view_name]
  WHERE [condition1] AND [condition2]
);

This will return results for spids that match the conditions in the IN sub-query. You don't need to include the DISTINCT there, since that just adds extra processing.

Upvotes: 0

zip
zip

Reputation: 4061

Like Gordon said above:

SELECT spid, status, hostname
FROM [view_namea]
WHERE spid IN (SELECT request_session_id
               FROM [view_nameb]
               WHERE [condition1] AND [condition2]
              );

Upvotes: 0

GMB
GMB

Reputation: 222402

I would us EXISTS with a correlated subquery. Unlike when using IN, this properly handles the case when the first query returns a request_session_id that is null:

SELECT spid, status, hostname
FROM [view_name] v1
WHERE EXISTS (
    SELECT 1
    FROM [view_name] v2
    WHERE 
        [condition1] 
        AND [condition2]
        AND v1.spid = v2.request_session_id
)

Note: likely, both [view_name]s belong to different tables; otherwise, the logic would be largely simplified.

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269483

Do you simply want IN?

SELECT spid, status, hostname
FROM [view_name]
WHERE spid IN (SELECT request_session_id
               FROM [view_name]
               WHERE [condition1] AND [condition2]
              );

Upvotes: 1

Related Questions