How to handle dynamic sql parameters

2020-03-26 03:33发布

问题:

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 and I have the parameter in the sql string will it screw or slow down the query?

回答1:

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<SqlParameter> cParameters = new List<SqlParameter>();

        // 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.



回答2:

One of the things that can be done is check whether the parameter was passed to your stored procedure. You can do it like this:

create procedure my_procedure (
  @param1 as int = null
  @param2 as int = null
) as 
begin

   select field1, field2, fieldn
     from table
    where ((@param1 is null) or (field2 = @param1))
      and ((@param2 is null) or (field2 = @param2))
end 

I'd rather do this on sql procedure than in the application tho