1

我正在尝试将 1 到 10 个条件传递给存储过程,该存储过程在下面的这个过程中使用下面的 select 语句:

ALTER PROCEDURE [dbo].[Original_Docs]  
@Cat varchar(255),
@docType VARCHAR(255),
@IdNo VARCHAR(50)

AS
BEGIN


SELECT 
    d4.id as DOCUMENT_ID, c.name as Category, dt.name as Document_Type, 
    mv1.value as GUIDELINE_MASTER, mv2.value as ID_NUMBER, mv3.value as [DATE],
    mv4.value as DESCRIPTION, mv5.value AS BUDGET_NUM, mv6.value as STATUS,
    mv7.value AS [CLOSED DATE], mv8.value AS REPORT_TYPE 
FROM Documents d4 
JOIN ( 
    SELECT d2.id 
    FROM Documents d2 
    JOIN (
        SELECT d.fileStoreId, MIN(d.createdDate) as CreatedDate 
        FROM Documents d 
        JOIN FileStores fs ON d.fileStoreId = fs.id 
        WHERE fs.shared = 1 AND d.dateDeleted IS NULL 
        GROUP BY d.fileStoreId
    ) AS f ON d2.fileStoreId = f.fileStoreId AND d2.createdDate = f.CreatedDate

    UNION 

    SELECT d3.id 
    FROM Documents d3 
    JOIN FileStores fs2 ON d3.fileStoreId = fs2.id 
    WHERE fs2.shared = 0 AND d3.dateDeleted IS NULL
) AS f2 ON f2.id = d4.id 
JOIN DocumentTypes dt ON d4.documentTypeId = dt.id 
JOIN Categories c ON dt.categoryId = c.id 
LEFT OUTER JOIN mv_guideline_master mv1 ON d4.id = mv1.documentId 
LEFT OUTER JOIN mv_id_number mv2 ON d4.id = mv2.documentId 
LEFT OUTER JOIN mv_date mv3 ON d4.id = mv3.documentId 
LEFT OUTER JOIN mv_description mv4 ON d4.id = mv4.documentId 
LEFT OUTER JOIN mv_budgetnum mv5 ON d4.id = mv5.documentId 
LEFT OUTER JOIN mv_status mv6 ON d4.id = mv6.documentId 
LEFT OUTER JOIN mv_closed_date mv7 ON d4.id = mv7.documentId 
LEFT OUTER JOIN mv_report_type mv8 ON d4.id = mv8.documentId 
WHERE c.name = @Cat AND (dt.name = @docType OR mv2.value = @IdNo) 
ORDER BY mv1.value 

在我弄清楚如何使用 3 个标准后,我将需要添加其余的其他标准。在 where 子句中,我传递参数@Cat、@docType 和@IdNo。如何使用这些条件进行查询,其中一个被另一个或 2 个空白填充?或者,如果所有这些都传入或仅传入 2 个。如果我使用 AND 然后它不起作用,或者如果我在标准之间使用 OR,它将带回错误的结果。我需要 Parens 在某个地方才能工作吗?

谢谢!

4

1 回答 1

0

不确定我是否完全遵循,如果每个变量都可以为 NULL:

WHERE (c.name = @Cat OR @Cat IS NULL) 
  AND ((dt.name = @docType OR @docType IS NULL)  
        OR (mv2.value = @IdNo OR @IdNo IS NULL)) 

或者如果为空:

WHERE (c.name = @Cat OR @Cat = '') 
  AND ((dt.name = @docType OR @docType = '')  
        OR (mv2.value = @IdNo OR @IdNo = '')) 
于 2013-09-30T15:40:16.920 回答