locked
Declare sql statement RRS feed

  • Question

  • User-1753299103 posted

    What is the most efficient method of declaring a sql statement at the top of the page:

    @{
      var db = Database.Open("database");
      int id=anynumber;
    
      var sql = ?
      
      if(id==1){
          sql = db.QuerySingle("select * from table where myid=@0", 5); 
      }
      if(id==2){
          sql = db.QuerySingle("select * from table where myid=@0", 6);  
      }
    
        @sql.myid
    
    }

    Wednesday, June 19, 2013 11:50 AM

Answers

  • User-821857111 posted

    dynamic sql = null;

    You still need to check to make sure that sql is not null before attempting to render sql.myId:

    @{ 
      var db = Database.Open("database");
      int id=anynumber;
    
      dynamic sql = null;
      
      if(id==1){
          sql = db.QuerySingle("select * from table where myid=@0", 5);
      }
      if(id==2){
          sql = db.QuerySingle("select * from table where myid=@0", 6);
      }
      if(sql != null){
          @sql.myid
      }
    }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 19, 2013 3:55 PM
  • User-1753299103 posted

    Thank you Mike,

    Your previous solution DynamicRecord sql = null; was the one that produced the error.

    The latter solution dynamic sql = null; worked perfectly!

     

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 19, 2013 4:28 PM

All replies

  • User-821857111 posted

    DynamicRecord sql = null;

    Wednesday, June 19, 2013 12:27 PM
  • User-1753299103 posted

    It produces the following error:

    'WebMatrix.Data.DynamicRecord' does not contain a definition for 'myid' accepting a first argument of type 'WebMatrix.Data.DynamicRecord' could be found (are you missing a using directive or an assembly reference?) 

    Wednesday, June 19, 2013 1:52 PM
  • User-821857111 posted

    dynamic sql = null;

    You still need to check to make sure that sql is not null before attempting to render sql.myId:

    @{ 
      var db = Database.Open("database");
      int id=anynumber;
    
      dynamic sql = null;
      
      if(id==1){
          sql = db.QuerySingle("select * from table where myid=@0", 5);
      }
      if(id==2){
          sql = db.QuerySingle("select * from table where myid=@0", 6);
      }
      if(sql != null){
          @sql.myid
      }
    }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 19, 2013 3:55 PM
  • User-1753299103 posted

    Thank you Mike,

    Your previous solution DynamicRecord sql = null; was the one that produced the error.

    The latter solution dynamic sql = null; worked perfectly!

     

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 19, 2013 4:28 PM