Querying the Result set of a Previous Query

五迷三道 提交于 2019-12-02 04:31:24

You can use the WITH clause

WITH SomeClients AS (
    SELECT
        c.ID
    FROM Clients c
    WHERE c.Name LIKE '%hello%'
)

SELECT DISTINCT
    sc.ID
FROM SomeClients sc
Zohar Peled

There are several ways to solve this:

1: create a view from the first query and run the second query on the view.

2: nest both queries, like this:

SELECT DISTINCT [Name]
FROM (
  SELECT [Name] 
  FROM table 
  WHERE some Criteria
) As InnerQuery

3: use a temporary table to store the resultset of the first query as suggested by wewesthemenace in the comments.

4: use CTE as suggested the thebreiflabb in the other answer to this post.

Personally, I would probably go with the first or second option, depending if you need to use the first query as stand alone as well.

You need WITH clause. The Syntax Is-

WITH someName AS(
 //Your Db Query
)
SELECT * FROM someName // OR Whatever you want

you can create a table to store the results temporarily and use that table in a new query

DECLARE @resultset table (
    ID   int identity(1,1) not null
  , name nvarchar(100)
)

Select top 50 application_Name
into  resultset
from Applications_ASIS
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!