I have to fight the desire to reduce duplication ... but a person that I really don't like.
Would it βfeelβ better?
SELECT ... lots of columns and complicated stuff ...
FROM
(
SELECT MyPK
FROM TBooks
WHERE
(--... SOME CONDITIONS)
AND @AuthorType = 1 AND --... DIFFERENT CONDITIONS)
union all
SELECT MyPK
FROM TBooks
WHERE
(--... SOME CONDITIONS)
AND @AuthorType = 2 AND --... DIFFERENT CONDITIONS)
union all
...
) AS B1
JOIN TBooks AS B2
ON B2.MyPK = B1.MyPK
JOIN ... other tables ...
Pseudo-table B1 is just a WHERE clause to get PK. Then it connects to the source table (and any others that are required) to get a "presentation". This avoids duplication of presentation columns in each UNION ALL.
You can do this again and insert PK into the temporary table first and then join it to other tables for the presentation aspect.
We do this for very large tables, where the user has many options that need to be completed.
DECLARE @MyTempTable TABLE
(
MyPK int NOT NULL,
PRIMARY KEY
(
Mypk
)
)
IF @LastName IS NOT NULL
BEGIN
INSERT INTO @MyTempTable
(
Mypk
)
SELECT MyPK
FROM MyNamesTable
WHERE LastName = @LastName - Lets say we have an efficient index for this
End
ELSE
IF @Country IS NOT NULL
BEGIN
INSERT INTO @MyTempTable
(
Mypk
)
SELECT MyPK
FROM MyNamesTable
WHERE Country = @Country - Got an index on this one too
End
... etc
SELECT ... presentation columns
FROM @MyTempTable AS T
JOIN MyNamesTable AS N
ON N.MyPK = T.MyPK - a PK join, V. efficient
JOIN ... other tables ...
ON ....
WHERE (@LastName IS NULL OR Lastname @LastName)
AND (@Country IS NULL OR Country @Country)
Note that all tests are repeated [technically you do not need @Lastname one :)], including obscure ones that (let's say) were not in the original filters to create @MyTempTable.
Creating @MyTempTable is designed to make the most of any setting. Perhaps if both @LastName and @Country are available, which populate the table much more efficiently than one of them, so we are creating a case for this scenario.
Scaling issues? Review what actual queries are in progress and add cases for those that can be improved.
Kristen
source share