Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8177039
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T23:24:29+00:00 2026-06-06T23:24:29+00:00

How can I add search condition to SQL Stored Procedure programmatically? In my application(C#)

  • 0

How can I add search condition to SQL Stored Procedure programmatically?
In my application(C#) I’m using stored procedure (SQL Server 2008R2)

ALTER PROCEDURE [dbo].[PROC001]
@userID varchar(20),
@password varchar(20)
AS
SELECT * FROM tUsers WHERE RTRIM(Name) = @userID AND RTRIM(Password) = @password

I want to extend this query by more conditions, and now I don’t know how many conditions will use this query due program execution.. 2, 3, 6 OR 20. I want to add these conditions programmatically like:

SELECT * FROM tUsers WHERE RTRIM(Name) = @userID AND RTRIM(Password) = @password
AND Field2 = '1' AND Field3 = '0' OR Field4 <> '8' AND Field5 < '100' ....

Is it possible to sent conditions to stored procedure dynamically?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T23:24:31+00:00Added an answer on June 6, 2026 at 11:24 pm

    Edit – Preference for LINQ based ORM’s, if possible

    If you don’t need to do this in ADO, a better solution is to use an ORM which will ultimately build parameterized ad-hoc sql. This is the best of both worlds – you get the flexibility of a dynamic query, with no redundant filters to upset the optimizer, the query plan itself is cacheable, and you are safe from nasties like injection attacks. And a Linq-based ORM query makes for easy reading:

     // Build up a non-materialized IQueryable<>
     var usersQuery = db.Users;
     if (!string.IsNullOrEmpty(userID))
     {
           usersQuery = usersQuery.Where(u => u.Name == userId);
     }
     // Of course, you wouldn't dream of storing passwords in cleartext.
     if (!string.IsNullOrEmpty(anotherField))
     {
           usersQuery = usersQuery.Where(u => u.AnotherColumn == anotherField);
     }
     ...
     // Materialize (and execute) the query
     var filteredUsers = usersQuery.ToList();
    

    For complex queries, you may want to look at PredicateBuilder

    ADO / manual query building

    You can use sp_executesql to build up SQL dynamically as per below. Provided that you parameterize the variables you should be safe from issues like SQL injection and escaping quotes etc will be handled for you.

    CREATE PROCEDURE [dbo].[PROC001]
        @userID varchar(20),
        @pwdHash varchar(20),
        @optionalParam1 NVARCHAR(50) = NULL -- Other optional parameters
    AS        
        BEGIN        
            SET NOCOUNT ON        
    
            DECLARE @SQL NVARCHAR(MAX)        
    
            -- Mandatory / Static part of the Query here. 
            -- Cleartext passwords are verboten, and RTRIM is redundant in filters
            SET @SQL = N'SELECT * FROM tUsers WHERE Name = @userID AND PwdHash = @pwdHash'
    
            IF @OptionalParam1 IS NOT NULL        
                BEGIN        
                    SET @SQL = @SQL + N' AND AnotherField = @OptionalParam1'    
                END        
    
            EXEC sp_executesql @SQL,        
                N'@userID varchar(20),
                @pwdHash varchar(20),
                @optionalParam1 NVARCHAR(50)'
                ,@userID = @userID
                ,@pwdHash = @pwdHash
                ,@optionalParam1 = @optionalParam1
        END
    

    Re, why is WHERE (@x IS NULL OR @x = Column) a bad idea?

    (From my comment below)

    Although the ‘optional parameter’ pattern works well as a ‘swiss army knife’ for querying a multitude of permutations of optional filters when used on small tables, unfortunately, for large tables, this results in a single query plan for all permutations of filters for the query, which can result in poor query performance with certain permutations of optional parameters due to the parameter sniffing problem. If possible, you should eliminate redundant filters entirely.

    Re: Why is applying functions in predicates a bad idea

    e.g.

    WHERE SomeFunction(Column) = @someParameter
    

    Use of functions in predicates frequently disqualifies the use of indexes by the RDBMS (“non-sargable”).

    In this instance, RTRIM is unnecessary as Sql server ignores trailing spaces during comparison.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can I add a database field to the Magento global search? I want
We can add an image to an photo album using UIImage *img = [UIImage
How do you add search to a layout so it can search for posts
I have a page where user dynamically add search condition(s) to filter out records.
I can add and remove the last line in my dynamic form and calculate
I can add a normal rightBarButton to my navigation without a problem but now
I can add a Conditional statement to a breakpoint, for instance arg0.startsWith(something) but i'd
Can someone please direct me on how I can add something similar to inputAccessoryView
I wrote library which can add and update objects in salesforce. I use beatbox
While we can add Inline Images in paragraphs there does not appear to be

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.