以下条件查询执行时间很长。我认为这取决于或条件。我如何替换这些或?
WHERE (p.tran_number = LTRIM(RTRIM(@tran_number)) OR ISNULL(LTRIM(RTRIM(@tran_number)), '') = '')
AND (CAST(p.fiscal_date AS DATE) >= CAST(@begin_date AS DATE) OR @begin_date IS NULL)
AND (CAST(p.fiscal_date AS DATE) <= CAST(@end_date AS DATE) OR @end_date IS NULL)
AND CAST(@end_date AS DATE)
AND (p.operation_type = @operation_type OR @operation_type = '-1')
AND (
ce.username = @username
OR @role_code LIKE '%admin%'
OR @role_code LIKE '%Statists_GO%'
OR (
(ce.username IN (
SELECT e.domain_username
FROM @childTable c
LEFT JOIN FstP.dbo.employees e ON e.id = c.obj_id
AND c.obj_type = 'employee'
)
)
AND @role_code LIKE '%supervisor%')
)
AND (p.rnm = @rnm OR ISNULL(@rnm, '') = '')
AND (ce.username = @author OR ISNULL(@author, '') = '')
AND (
d2.docs_num = @policy_number
OR dGate.DealNumber = @policy_number
OR ISNULL(@policy_number, '') = ''
)
ORDER BY insert_date DESC, fiscal_date DESC
答案 0 :(得分:1)
SET @begin_date = CAST(@begin_date AS DATE)
SET @end_date = DATEADD(DAY, 1, CAST(@end_date AS DATE))
SET @tran_number = LTRIM(RTRIM(@tran_number))
...
WHERE (p.tran_number = @tran_number OR ISNULL(@tran_number, '') = '')
AND (p.fiscal_date >= @begin_date OR @begin_date IS NULL)
AND (p.fiscal_date < @end_date OR @end_date IS NULL)
AND (p.operation_type = @operation_type OR @operation_type = '-1')
AND (
ce.username = @username
OR @role_code LIKE '%admin%'
OR @role_code LIKE '%Statists_GO%'
OR (
ce.username IN (
SELECT e.domain_username
FROM @childTable c
JOIN FstP.dbo.employees e ON e.id = c.obj_id
AND c.obj_type = 'employee'
)
AND @role_code LIKE '%supervisor%'
)
)
AND (p.rnm = @rnm OR ISNULL(@rnm, '') = '')
AND (ce.username = @author OR ISNULL(@author, '') = '')
AND (
d2.docs_num = @policy_number
OR dGate.DealNumber = @policy_number
OR ISNULL(@policy_number, '') = ''
)
ORDER BY insert_date DESC, fiscal_date DESC
OPTION(RECOMPILE)