简体   繁体   中英

sql server how to reuse where conditions in multiple queries with different returning results

I have a huge sql query with multiple joins and bundle of where conditions (filters). The query returns results with pagination or page wise. Now in other case I need only a total count as result instead of records list based on same applied filters. One way is to repeat/copy the same query and changing the SELECT clause plus removing the pagination OFFSET @PageSize * (@PageIndex - 1) ROWS FETCH NEXT @PageSize ROWS ONLY and all the WHERE conditions would be repeated, so in future if there's any change I have to change both queries. Is there any way around to reuse all the WHERE conditions since only the selection is being changed?

First query:

SELECT Id,Name
FROM Users
WHERE 1=1
...bundle of where conditions
ORDER BY Name
OFFSET @PageSize * (@PageIndex - 1) ROWS FETCH NEXT @PageSize ROWS ONLY

Second query:

SELECT COUNT(1)
FROM Users
WHERE 1=1
...reuse above bundle of where conditions

Two options spring to mind.

Dynamic SQL is your friend here but a more pragmatic design using Views will allow you to centralise the where clauses....

If you need to adjust the WHERE clauses you simply change the view implementation, this will allow to cascade the updates everywhere the view is used.

Create View vwCustomUsers
SELECT Id,Name
FROM Users
WHERE 1=1
...bundle of where conditions


SELECT Id,Name
FROM vwCustomUsers
WHERE 1=1
ORDER BY Name
OFFSET @PageSize * (@PageIndex - 1) ROWS FETCH NEXT @PageSize ROWS ONLY

SELECT COUNT(1)
FROM vwCustomUsers
WHERE 1=1

If it is relevant to you, you can do it two ways I can think of

I didn't test, but query would be like this:

  1. With store procedure: create a store procedure with parameters, while querying, store store procedure out in a temp table and join with other table

  2. Create a prameterized function and you can cross apply with your other tables.

1. For store proredure

Suppose our store procedure name is SelectFilteredUsers .

CREATE PROCEDURE SelectUsersWithFilter @param1 @param2
AS
SELECT * FROM Users WHERE --- --- ---
GO;

Later query would be

INSERT INTO #Temp
EXEC SelectFilteredUsers(@param1, @param2)

SELECT Id,Name
FROM #Temp
WHERE 1=1
ORDER BY Name
OFFSET @PageSize * (@PageIndex - 1) ROWS FETCH NEXT @PageSize ROWS ONLY

2. With functions

CREATE FUNCTION dbo.SelectUsersWithFilter (@params)
RETURNS @retFindReports TABLE .....

and you can do like

SELECT Id,Name
FROM dbo.fn_MarketDataDetails (@params)
ORDER BY Name
OFFSET @PageSize * (@PageIndex - 1) ROWS FETCH NEXT @PageSize ROWS ONLY

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.

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