where clause

10-21-2019 01:32 PM
New Contributor II

How do I pass a text value from a GetParameterAsText into a where clause:


Within a geodatabase feature class ( FC ) is an attribute = Title

Title has several rows that have "Seal" within the title such as "Harbor Seals within Cook Inlet", "Seal Population near Point Lay", etc.

I want to create a Python Tools where the user can input a word search from the Title attribute = Seals 

input = arcpy.GetParameterAsText(0)  # input = "Seal"

cursor = arcpy.SearchCursor(fc, "Title LIKE input")  # obviously this line of code does not work

I need to include a "where clause" that include the "input" = seals


0 Kudos
3 Replies
by Anonymous User
Not applicable

I haven't tested the code but just looking at it, I assume the expression in the following format would work. Can you try the below expression? 

input = arcpy.GetParameterAsText(0)  # input = "Seal"
expression = "TITLE LIKE '" + input + "%'"
cursor = arcpy.SearchCursor(fc, expression)‍‍‍‍‍‍

Also refer the following links for more examples on using the where clause

SearchCursor—Help | ArcGIS for Desktop 

Problems using the where clause with searchcursor method  

cursor - Not Able to Pass Where Clause in SearchCursor in ArcPy - Geographic Information Systems Sta...  



MVP Esteemed Contributor

As written, the expression will only find rows that start with "Seal."  The following expression will capture seal anywhere and regardless of case:

input = arcpy.GetParameterAsText(0)  # input = "Seal"
expression = "LOWER(TITLE) LIKE '%" + input.lower() + "%'"
cursor = arcpy.SearchCursor(fc, expression)
0 Kudos
Occasional Contributor III

Ravi's answer should work for you. If you want an exact match for your input parameter you could use:

input = arcpy.GetMarameterAsText(0)
# python 2 str.format() function inserts the string variable into your expression with out needing to concatenate strings
expression = "TITLE = '{}'".format(input) 
cursor = arcpy.da.SearchCursor(fc, expression)‍‍‍‍

Tip: you may wish to use the data access module search cursor (as I've demonstrated above) if you are using a recent release of ArcGIS. It works the same but faster!

SearchCursor—Help | ArcGIS for Desktop

0 Kudos