title: Check to see if variable exists..inline sql
body: <p>SQL Server 2016 .Net 4.5.2 C#</p>
  
  <p>I say this with respect, I am using the Northwind database to show what I'm trying to achieve. Please, no comments about the Northwind database. This is just an example of what i will be doing.</p>
  
  <p>I am using ADO.Net to execute inline sql. My dilemma is i will have optional parameters that might be passed to the sql query. Here's the C#:</p>
  
  <pre><code>var city = "";
  var state = "tx";
  var sqlQuery = "
         if exists @City
         begin
         select * from Customers where city = @City and state=@State;
         end
         else
         begin
          select * from Customers where state=@State;
         end
      ";
  
  var conn =  new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
  conn.Open();
  SqlCommand cmd = new SqlCommand(sqlQuery, conn);
  
  if (!string.IsNullorEmpty(city))
  {
      SqlParameter param  = new SqlParameter();
      param.ParameterName = "@City";
      param.Value         = city;
      cmd.Parameters.Add(param);
  }   
  
  if (!string.IsNullorEmpty(state))
  {
      SqlParameter param  = new SqlParameter();
      param.ParameterName = "@State";
      param.Value         = state;
      cmd.Parameters.Add(param);
  }
  
  var reader = cmd.ExecuteReader();
  </code></pre>
  
  <p>As you can see, the variable city is blank so the parameter @City will not be passed to the sql query, but the variable state is not blank so @State parameter will be passed to the query. Keep in mind, @City will not be blank all the time. I put a check in the sql to see if @City exists, but that does not work. How do I check in the sql query if @City, @State or any other parameters that might be passed in exist? If i can figure that part out, I can handle what needs to be done in the sql. Thanks for any and all help.</p>
  
  <p>P.S. I cannot use stored procedures. </p>