Question : Get value from a specific field based on the value of an another field in the same query?

How can I get the value from a field in an Access SQL query bases on the value of another field in the same query? See example below.

     Table1:
     ID       Label     FieldNumber
     ------------------------------------
     1        Name        15

    Tabel2:
     ID       Field3     Field15     Field22
     -----------------------------------------------
     1        224         Nick         Rotterdam

I have made a query that links Tabe1 and Table2 on the field ID. In that query I also want to get the value from the field where FieldNumber is pointing at. In this example field Field15. What makes it difficult is that the FieldNumber for Label ‘Name’ can change: 15 or 18 (depending on the administration the data is coming from). I have tried to solve this with using an IIF() function in my query.

        IIF(FieldNumber=15; [Field15]; IIF(FieldNumber=18; [Field18];””))

The problem is that this solution fails if Field15 or Field18 is not in Table2. The IIF() function evaluates all options and the query will ask for manual input (missing parameter). This will happen if FieldNumber for Label ‘Name’ is 18 and Field15 is not in Table2.

Is there another solution to get the value from a specific database field in a Access query based on the value of an another field in the same query?

Answer : Get value from a specific field based on the value of an another field in the same query?

If you are linked to the SQL table this should work:

SELECT t1.ID, t1.Label, t1.FieldNumber, GetValue(t1.ID,t1.FieldNumber) FROM Table1 AS t1 ORDER BY t1.ID

Now the UDF - in a Standard Module, not a class module (behind a form)

Public Function GetValue(myID as Long, fldNo as Integer) AS String
Dim db as Database, rs as Recordset
Set db = Currentdb
Set rs = db.Openrecordset("SELECT Field" & fldNo & " FROM Table2 WHERE ID = " & fldNo & ";", dbOpenSnapShot)
If rs.EOF OR rs.BOF Then
  GetValue = "No Value"
Else
  GetValue = rs.Fields("Field" & FldNo).Value
End If
Set rs = Nothing
Set db = Nothing
End Function


Random Solutions  
 
programming4us programming4us