sql query where with condition

Spunny 326 Reputation points
2024-05-02T22:32:38.0266667+00:00

Hi, I have a query same but only one of the where clauses differ.

If (@accountID = 100)
Begin

select field1, field2

FROM table1

left outer join table 2

where status = 'x'

and ISNULL(accountid, @accountID) = @accountID

END

Else

select field1, field2

FROM table1

left outer join table 2

where status = 'x'

and accountID = @accountID OR @subAccount In (table1.checkinaccount, table1.savingsaccount) or remarks like @searchstring

END

How do I make it into 1 sql query and have

ISNULL(accountid, @accountID) = @accountID and accountID = @accountID OR @subAccount In (table1.checkinaccount, table1.savingsaccount) or remarks like @searchstring based on accountid

Thanks

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,851 questions
SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
48 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,559 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. CosmogHong-MSFT 23,556 Reputation points Microsoft Vendor
    2024-05-03T01:35:23.9466667+00:00

    Hi @Spunny

    I have a query same but only one of the where clauses differ. How do I make it into 1 sql query and have

    Why you want a single query? Cause it is not only about merging two where conditions together, but also about writing the IF Else condition into it. In my opinion, this is an unnecessary action, and your current statement is logical enough.

    Personally, it is recommended to seek optimization on the premise of clarifying the logic of the statement.

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    0 comments No comments