code_junkie

Is there a standard approach to generating sql dynamically?

Nov 10th, 2011
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. sqlCmd.CommandText = "DECLARE @t Table(ContactId int, ROWRANK int" + declare
  2. + ")INSERT INTO @t(ContactId, ROWRANK" + insertFields + ")"//Insert as few cols a possible
  3. + "Select ContactID, ROW_NUMBER() OVER (ORDER BY " + sortExpression + " "
  4. + sortDirection + ") as ROWRANK" // generates a rowrank for each row
  5. + outerFields
  6. + " FROM ( SELECT c.id AS ContactID"
  7. + coreFields
  8. + from // sometimes different tables are required
  9. + where + ") T " // user input goes here.
  10. + groupBy+ " "
  11. + havingClause //can be empty
  12. + ";"
  13. + "select @@rowcount as rCount;" // return 2 recordsets, avoids second query
  14. + " SELECT " + fields + ",field1,field2" // join onto the other cols n the table
  15. +" FROM @t t INNER JOIN contacts c on t.ContactID = c.id"
  16. +" WHERE ROWRANK BETWEEN " + ((pageIndex * pageSize) + 1) + " AND "
  17. + ( (pageIndex + 1) * pageSize); // here I select the pages I want
  18.  
  19. //Add Parameter to SQL Command
  20. AddParamToSQLCmd(sqlCmd, "@p" + z.ToString(), SqlDbType.VarChar, 50, ParameterDirection.Input, qc.FieldValue);
  21. // Create SQL code Fragment
  22. where.AppendFormat(" {0} {1} {2} @p{3}", qc.BooleanOperator, qc.FieldName, qc.ComparisonOperator, z);
  23.  
  24. string query= "SELECT {0} FROM .... WHERE {1}"
  25. StringBuilder selectclause = new StringBuilder();
  26. StringBuilder wherecaluse = new StringBuilder();
  27.  
  28. // .... the logic here will vary greatly depending on what your system looks like
  29.  
  30. MySqlcommand.CommandText = String.Format(query, selectclause.ToString(), whereclause.ToString());
  31.  
  32. List<Expression> expressions = new List<Expression>(userConditions.Count);
  33. foreach(Condition c in userConditions)
  34. {
  35. expressions.Add(Expression.Eq(c.Field, c.Value));
  36. }
  37. SomeTable[] records = SomeTable.Find(expressions);
  38.  
  39. where...
  40. and (@MyParam5 is null or @MyParam5 = Col5)
Add Comment
Please, Sign In to add comment