简体   繁体   中英

sql server using where criteria for multiple values being passed

I am trying to pass from 1 to 10 criterias to a stored procedure that uses a select statement below in this procedure below:

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 

I will need to add the rest of the other criteria after I figure out how to do it with 3 criteria. In the where clause, I am passing parameters @Cat, @docType, and @IdNo. how do I query using these criteria with the one of these being filled in with the other one or 2 blank? Or if all of them where passed in or if only 2 were passed in. If I use AND then it doesn't work or if I use OR between the criteria, it will bring back the wrong result. Do I need Parens somewhere for it to work?

thanks!

Not sure I follow exactly, if each variable can be 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)) 

or if blank:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM