0

suppose i have this code snippet

Dim tab As String = "myTab"
Dim val As String = "field1"
Dim con As String = "...."
Dim qry As String 'should be: "Select * from " & tab & " where value = '" & val & "'"
Dim com As New OracleCommand (qry, con)...

suppose also that the query string (ie the value of qry) is retrieved from a database. I can not pass qry to the oracle command, because it would not be evaluated, ie variables are not bound to their values, and the string is passed literally to the command, causing an error. is there a way to evaluate a string and execute it as a VB statement?

mr anto
  • 23
  • 1
  • 6
  • 1
    Try using parameters, your solution is so simple! – muffi Nov 07 '17 at 10:19
  • muffi. the query string was just an example. I should store various code strings, to be retrieved and evaluated at runtime. for example, I wish to store a where clause of a query, then extract, evaluate and pass it to a report.So, I was looking for somewhat like the "Eval" statement of javascript – mr anto Nov 07 '17 at 11:40
  • You want to store a sql query with parameters put the parameters will be passed at runtime? – Chillzy Nov 07 '17 at 18:37
  • chillzy, not necessarily a query string. I wish to store a generic string, in order it would be executed at runtime. for example, if I have declared a variable val = "field1", and provide at runtime the string value = '" & val & "'" I wish to get something like this value = 'field1' – mr anto Nov 08 '17 at 08:37

1 Answers1

1

Using parameters is so simple as @muffi said.

Off the top of my head:

    Dim tab As String = "myTab"
    Dim val As String = "field1"

    Using cmd As New OracleCommand("SELECT * FROM :table WHERE value = :value", con)
        cmd.Parameters.Add(New OracleParameter() {Direction = ParameterDirection.Input, ParameterName = "table", OracleDbType = OracleDbType.Varchar2, Value = tab})
        cmd.Parameters.Add(New OracleParameter() {Direction = ParameterDirection.Input, ParameterName = "value", OracleDbType = OracleDbType.Varchar2, Value = val})
        Using OracleDataReader reader As cmd.ExecuteReader()
            While reader.Read()
                Console.WriteLine(reader.GetString(0))
            End While
        End Using
    End Using
ɐsɹǝʌ ǝɔıʌ
  • 4,440
  • 3
  • 35
  • 56
  • thank you for your answer. As I was saying to muffi, I need somewhat more general than a query string. for example, I should save into db only the where clause of a query: " WHERE value = '" & val & "'". At runtime, I wish to retrieve this string, evaluate it (transform in " WHERE val = 'field1'"), and pass it as a parameter to a crystal report. May I get it? – mr anto Nov 07 '17 at 14:58