Select layer by attribute does not work in standalone script, does in arcmap

2733
2
Jump to solution
01-23-2013 04:54 AM
MennoNijhuis2
New Contributor
I'm having trouble with the SelectLayerByAttribute_management() tool. Although it produces no errors or whatsoever, I get an empty selection.

This is the code I am using in my standalone script. I've run it down to the part that's causing trouble and added lots of checks
import arcpy database = 'D:/Menno/openhabitat/Keillour/HabitatSDM/Habitats.gdb' fc = database + '/SurveyData/HabitatSiteArea' subs = ['504S34','504S35'] sql = """ "PolygonNo" = '%s' """ lyr = 'lyr'  # create empty layer to add features to arcpy.MakeFeatureLayer_management(fc,lyr,sql % '') print 'layer exists:', arcpy.Exists(lyr) print 'features in lyr:', arcpy.GetCount_management('lyr').getOutput(0) print 'featureclass exists:', arcpy.Exists(fc) print 'features in feature class:', arcpy.GetCount_management(fc).getOutput(0) l = arcpy.ListFields(fc) m = [] for a in l:     m = m + [a.name] print 'field exists in featureclass:', 'PolygonNo' in m  # loop along PolygonNos and add each feature to the selection layer for f in subs:     print 'PolygonNo:', f     print 'Sql:', sql % f     arcpy.SelectLayerByAttribute_management(lyr,'ADD_TO_SELECTION', sql % f)     print 'Features in lyr after select:', arcpy.GetCount_management(lyr).getOutput(0) ##arcpy.DeleteFeatures_management(lyr) print 'End'


This evaluates to:
layer exists: True features in lyr: 0 featureclass exists: True features in feature class: 60 field exists in featureclass: True PolygonNo: 504S34 Sql:  "PolygonNo" = '504S34'  Features in lyr after select: 0 PolygonNo: 504S35 Sql:  "PolygonNo" = '504S35'  Features in lyr after select: 0 End


As you can see, layer exists, feature class exists, field exists, there are features in the featureclass, and on my word, there are also features with the mentioned attributes.

Performing a select by attributes from the arcmap menu or arcmap attribute table view, using the exact same sql phrases does result in a selection. Copying the lines one by one to the arccatalog or arcmap script window does not.
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
MathewCoyle
Frequent Contributor
This is your problem here. You have a layer with no features in it because of your query. Remove the query.
arcpy.MakeFeatureLayer_management(fc,lyr,sql % '')

View solution in original post

0 Kudos
2 Replies
MathewCoyle
Frequent Contributor
This is your problem here. You have a layer with no features in it because of your query. Remove the query.
arcpy.MakeFeatureLayer_management(fc,lyr,sql % '')
0 Kudos
MennoNijhuis2
New Contributor
That did the trick, thanks mzcoyle 🙂
I had this thought in my head that I first needed to have an empty layer before using add_to_selection to step by step increase the number of features in the layer. But apparently, the layer I created with makefeaturelayer had no selection on it, just a definition query.
0 Kudos