title: Safely get next SQL Server sequence value from .NET
body: <p>I'm experimenting with SEQUENCE objects in SQL Server, and getting the next value with C# by specifying the sequence name. Ranges are simple, because there is a stored procedure for them, and you can pass the sequence name;</p>
  
  <pre><code>    public static T Reserve&lt;T&gt;(string name, int count, SqlConnection sqlConn)
      {
          using (var sqlCmd = new SqlCommand("sp_sequence_get_range", sqlConn))
          {
              sqlCmd.CommandType = CommandType.StoredProcedure;
              var firstValueParam = new SqlParameter("@range_first_value", SqlDbType.Variant) { Direction = ParameterDirection.Output };
  
              sqlCmd.Parameters.AddWithValue("@sequence_name", name);
              sqlCmd.Parameters.AddWithValue("@range_size", count);
              sqlCmd.Parameters.Add(firstValueParam);
  
              sqlCmd.ExecuteNonQuery();
  
              return (T)firstValueParam.Value;
          }
      }
  </code></pre>
  
  <p>But what about single values? It seems to me that I can either call the above with a count of '1', or I can construct the SQL dynamically. i.e.</p>
  
  <pre><code>var sqlCmdStr = string.Format("SELECT NEXT VALUE FOR {0}", name);
  </code></pre>
  
  <p>Which I know to generally be bad practice (i.e. SQL injection).</p>
  
  <p>What would anyone suggest?</p>