I have developing the MVC application for generating the report. I have provided many search option like below
Customer id
Customer name
Customer E-mail
State
Country
User 1:
If the some user will give inputs to only some Values like
Customer id = 1
Customer name = A
By default other parameters are passed as null to the stored procedure.
Customer E-mail
State
Country
User 2:
If the some user will give inputs to only some values like
Customer [email protected]
By default other parameters are passed as null to the stored procedure.
Customer id
Customer name
State
Country
How can i use the where clause in the SQL query in the stored procedure. Can we do it like below
string qry = select * from table_name where status != d
if (@customerID!=null)
qry = qry + "and customer_id=@customerID"
if (@customerName!=null)
qry = qry + "and customer_name=@customerName"
Please let me the best approach on this.
Thanks, Velu
The SELECT query will display only the records satisfying the condition specified in the WHERE clause There can be one or more than one condition specified in WHERE clause condition of a SELECT query. The AND and OR operators are used to check multiple conditions using the WHERE clause in a single query.
Syntax. The basic syntax of the SELECT statement with the WHERE clause is as shown below. SELECT column1, column2, columnN FROM table_name WHERE [condition] You can specify a condition using the comparison or logical operators like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear.
The WHERE clause follows the SELECT and the FROM clauses. While the SELECT clause specifies the columns to be returned from the table (s), the WHERE clause contains the conditions that must evaluate to true for a row to be returned as a result. Each condition is evaluated for each row returned from the table (s).
SQL requires single quotes around text values (most database systems will also allow double quotes). The following operators can be used in the WHERE clause: Not equal. Note: In some versions of SQL this operator may be written as !=
If you are creating dynamic SQL then you can do just like you are above:
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = 'SELECT * FROM TABLE '
if (@customerID IS NOT NULL)
SQL = SQL + " AND customer_id = @customerID"
Or another option is to handle it like
SELECT *
FROM TABLE
WHERE (@customerID IS NULL OR customer_id = @customerID)
I prefer the second as it is utilizing parametrized variable. First example needs to take into consideration malicious input far more intensely.
You could do dynamic SQL, but a simpler method is:
WHERE (ISNULL(@param1,1) = 1 OR [col1] = @param1)
AND (ISNULL(@param2,1) = 1 OR [col2] = @param2)
AND ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With