I have a basic SQL query, starting with:
SELECT top 20 application_id, [name], location_id FROM apps
Now, I would like to finish it so that it
See this entry in my blog:
If your @lid is a comma-delimited list of integers, use this:
WITH cd AS
(
SELECT 1 AS first, CHARINDEX(',', @lid, 1) AS next
UNION ALL
SELECT next + 1, CHARINDEX(',', @lid, next + 1)
FROM cd
WHERE next > 0
),
lid AS
(
SELECT CAST(SUBSTRING(@lid, first, CASE next WHEN 0 THEN LEN(@lid) + 1 ELSE next END - first)AS INT) AS id
FROM cd
)
SELECT d.*
FROM (
SELECT DISTINCT id
FROM lid
) l
JOIN apps a
ON a.location_id = l.id
AND @lid <> '0'
UNION ALL
SELECT *
FROM apps a
WHERE @lid = '0'
This is much more efficient than using OR constructs.