How to handle dynamic sql parameters

前端 未结 2 1084
囚心锁ツ
囚心锁ツ 2021-01-14 09:02

What is a good way to handle dynamic sql parameters?

I have a search form that takes in a whole bunch of different search parameters. If the parameters are empty an

2条回答
  •  旧时难觅i
    2021-01-14 09:12

    Depending on the specific implementation, we have two general approaches to this problem:

    1) Dynamically build the filter statement for the SQL query in code skipping any parameters that are empty. This is the best approach if you allow the user to select multiple values for a single column (i.e. select 0 or more of the 50 states to filter the data).

    For example:

    Assuming txtCondition1 and txtCondition2 are textboxes:

            // Assuming conn is an open SqlConnection
    
            System.Text.StringBuilder sbSQL = new StringBuilder(500);
    
            List cParameters = new List();
    
            // Add a default condition of 1=1 so that all subsequent conditions can be added 
            // with AND instead of having to check to see whether or not any other conditions
            // were added before adding AND.
            sbSQL.Append("SELECT * FROM MyTestTable WHERE 1 = 1 ");
    
            if (!String.IsNullOrEmpty(txtCondition1.Text)) {
                sbSQL.Append(" AND Column1 = @Column1");
                cParameters.Add(new SqlParameter("@Column1", txtCondition1.Text));
            }
            if (!String.IsNullOrEmpty(txtCondition1.Text))
            {
                sbSQL.Append(" AND Column2 = @Column2");
                cParameters.Add(new SqlParameter("@Column2", txtCondition2.Text));
            }
    
            SqlCommand oCommand = new SqlCommand(sbSQL.ToString, conn);
            if (cParameters.Count != 0) 
            {
                oCommand.Parameters.AddRange(cParameters.ToArray());
            } 
    
            // Do something with oCommand
    

    2) If the values are more constrained, we usually pass them to a stored procedure, which is responsible for determining whether or not the value is to be evaluated by testing the parameter for "emptinesss", either null, empty string, 0 for numerics, etc.

提交回复
热议问题