We help IT Professionals succeed at work.

Passing varaible into SQL statement

wilnah
wilnah asked
on
I want to pass in a variable to replace the field name of a table.  I need the correct syntax.  i.e.

Dim strsql As String, strdte As String
strdte = "9/24"
strsql = "SELECT tblenviroment.Enviroment, tblenviroment.(strsql) FROM tblenviroment WHERE (((tblenviroment.(strsql)) Is Not Null));"
Me.RecordSource = strsql


I need help with the - - tblenviroment.(strsql) syntax.  
I tried tblenviroment. & [strsql] & - - among others with no luck.
Comment
Watch Question

ok you want to be able to select a different field from a table, based on a variable right? well here is the syntax

Public Sub SetSQL(ByVal FieldName as String)
   Dim SQL As String
   SQL = "SELECT Enviroment, [" & FieldName & "] AS TempField"
   SQL = SQL & " FROM tblenviroment"
   SQL = SQL & " WHERE ([" & FieldName & "] Is Not Null);"
   Me.RecordSource = SQL
End Sub

then you can bind your textboxes to the fields 'Environment' and 'TempField' and they should display correctly for whatever field you select.

Commented:
Try this:

strsql = "SELECT tblenviroment.Enviroment, tblenviroment.[" & strsql & "]" & " FROM tblenviroment WHERE (tblenviroment.[" & strsql & "]" & "
Is Not Null);"

Explore More ContentExplore courses, solutions, and other research materials related to this topic.