添加/跳過哪裏條款我有下面的查詢,它從表變量中獲取TagId列表並返回列表。基於條件
但我需要添加該CategoryId WHERE條件只有@Tags有記錄。
只有當我的表變量有記錄才能添加WHERE條件,否則運行1 = 1(總是爲true)的相同查詢並跳過類別過濾器?
DECLARE @TagIdList NVARCHAR(100) = '22,25,47'
DECLARE @Tags TABLE (TagId INT);
WITH CSVtoTable
AS (
SELECT CAST('<XMLRoot><RowData>' + REPLACE(t.val, ',', '</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
FROM (
SELECT @TagIdList
) AS t(val)
)
INSERT INTO @Tags (TagId)
SELECT m.n.value('.[1]', 'varchar(8000)') AS TagId
FROM CSVtoTable
CROSS APPLY x.nodes('/XMLRoot/RowData') m(n)
SELECT BookingId
,C.CategoryName
FROM Booking B
INNER JOIN Category C ON C.CategoryId = B.CategoryId
WHERE (
b.IsDeleted = 0
OR b.IsDeleted IS NULL
)
-- Add the below where condition only if @Tags has records, else use 1=1
AND C.CategoryId IN (
SELECT DISTINCT CategoryId
FROM CategoryXTag con
WHERE TagId IN (
SELECT TagId
FROM @Tags
)
)
這看起來很簡單,很有效 – Developer