0

I want to pass a user defined variable into a where clause

Syntax

SelectLayerByAttribute_management (in_layer_or_view, {selection_type}, {where_clause})

#user input
MTRsel = arcpy.GetParameterAsText(0)

#put user input into where clause arcpy.SelectLayerByAttribute_management("Townships","NEW_SELECTION", "MTR" = + MTRsel)

I have tried many variations of this but it will not accept it, what am I missing

alaskangraham
  • 19
  • 1
  • 6
  • 3
    You asked this exact same question previously here, which itself is a nearly exact duplicate of this one. Try to avoid asking the same question repeatedly. – blah238 Feb 27 '14 at 20:26

2 Answers2

4

I think the safest and clearest way to specify a where_clause argument is to use a triple-quoted string with Python's format() method.

If the MTR field is formatted as numeric:

''' "MTR" = {0} '''.format(MTRsel)  # no quotes around value

Or, if the MTR field is formatted as text:

''' "MTR" = '{0}' '''.format(MTRsel)  # single-quotes around value

Note that the field name must be surrounded by double quotes if you're working with a shapefile or a file geodatabase (.gdb). If your data is in a personal geodatabase (.mdb), you'll have to switch the quotes to square-brackets:

''' [MTR] = {0} '''.format(MTRsel)
nmpeterson
  • 8,276
  • 33
  • 59
1

at a first glance, you should use (if MTRsel is a number)

arcpy.SelectLayerByAttribute_management("Townships","NEW_SELECTION", '"MTR" =' + MTRsel)

because python needs to interprete your whereclause as a string. You should also check that "Townships" is a valid name of layer (create by makeFeatureLayer).

EDIT : If MTRsel is a string, it should also be placed between quotes.

arcpy.SelectLayerByAttribute_management("Townships","NEW_SELECTION", '"MTR" =' + "'"+ MTRsel +"'")

a good practice to debug this kind of problem is to print your whereclause using, e.g.,

print '"MTR" =' + "'"+ MTRsel +"'"

the output has to be a valis sql statement (you can check interactively with ArcGIS select by attribute.

radouxju
  • 49,636
  • 2
  • 71
  • 144