2

I have created python script tool in arcgis 10.1 as below. I am trying to take input parameter and passing to select statement.

There is error when i execute this tool.

import arcpy

from arcpy import env

env.workspace = "Database Connections\sc_dev.sde"

name = arcpy.GetParameterAsText(0)

arcpy.SelectLayerByAttribute_management ("SC.STATES", "NEW_SELECTION", " \"STATE_NAME\" = name")

The error is Failed to execute....Invalid expression..ERROR 000358

2

I am going to assume that name is set to a string and that STATE_NAME is a text field.

In which case I think this should work.

Change:

arcpy.SelectLayerByAttribute_management ("SC.STATES", "NEW_SELECTION", " \"STATE_NAME\" = name")

to:

arcpy.SelectLayerByAttribute_management ("SC.STATES", "NEW_SELECTION", '"STATE_NAME" = ' + "'" + name + "'")

Note how I:

  • enclose "STATE_NAME" = inside single quotes (because the field name is delimited by double quotes);
  • enable the name variable to be evaluated by not having quotes around it
  • need to place single quotes around the value of name, which I do by enclosing each of them in double quotes.

The below syntax will also work, and is the way that I would normally do it nowadays:

arcpy.SelectLayerByAttribute_management ("SC.STATES", "NEW_SELECTION", "STATE_NAME = '{0}'".format(name))

The above uses Python formatting syntax to construct the where_clause.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.