Search code examples
sqlsql-servervb.netsql-server-2012localdb

SQL LocalDB SELECT statement with multiple conditions


I created a stored procedure for my .NET project and it goes like this,

ALTER PROCEDURE [dbo].[Search_PM_SELECTED]
(
    @acID varchar(50),
    @pmCat varchar(50),
    @pmTitle varchar(50),
    @pmUsername varchar(50),
    @pmSiteURL varchar(100)
)
AS
    SELECT * FROM pmPassword
    WHERE acID  = @acID and
    pmCat like '%' + @pmCat + '%' or
    pmTitle like '%' + @pmTitle + '%' or
    pmUsername like '%' + @pmUsername + '%' or
    pmSiteURL like '%' + @pmSiteURL + '%';

What I'm trying to accomplish is to select all records that match those fields except that they must be within acID. To further explain please take a look below;

 acID    pmCat      pmTitle    pmUsername       pmSiteURL  
 1      Windows     Google       MyName     www.somewhere.com     
 2      Network     FTP          MyName     www.somewhere.com  

Above should look like a table. I only want to show the items with acID = 1

Please take note that acID does auto increment whenever I add a record which is what I have accomplished in VB alone. acID is not a PK. My PK is pmID which is not included in the query because I have no use for it.

I am working with VB and SQL LocalDB (2012).


Solution

  • AND has higher precendence than OR. You need to add parentheses to get what you want:

    SELECT *
    FROM pmPassword
    WHERE acID = @acID
    AND
    (
        pmCat LIKE '%' + @pmCat + '%' 
        OR pmTitle LIKE '%' + @pmTitle + '%'
        OR pmUsername LIKE '%' + @pmUsername + '%'
        OR pmSiteURL LIKE '%' + @pmSiteURL + '%'
    );
    

    Your query is interpreted as follows:

    SELECT *
    FROM pmPassword
    WHERE (acID = @acID AND pmCat LIKE '%' + @pmCat + '%')
    OR pmTitle LIKE '%' + @pmTitle + '%'
    OR pmUsername LIKE '%' + @pmUsername + '%'
    OR pmSiteURL LIKE '%' + @pmSiteURL + '%'