I have a Python GP tool on our Arc GIS Server that generates a report based on a polygon drawn on a web map. I have a query that sorts up to the top 15 cities in the region by population and creates a temporary shapefile of these cities. Everything works fine until I have a small enough region that only has one populated city. I get this error from the server logs:
An invalid SQL statement was used. An invalid SQL statement was used. The Project method cannot do a datum transformation. Failed to execute (FeatureClassToFeatureClass).
I do not get this error if there are two or more populated cites in the region. Here is the Python snippet with the query. It's set to skip the temporary shapefile creation if there are no cities in the region.
cities = temp_path + region_name + "\\" + "cities.shp"
values = [row[0] for row in arcpy.da.SearchCursor(cities, field)]
top_cities = sorted(values)[-15:] #adjust max rows count
query = "\"{0}\" in {1}".format(field, tuple(top_cities))
check_list = [cities,]
for shapefile in check_list:
if arcpy.GetCount_management(shapefile)[0] != 0:
arcpy.FeatureClassToFeatureClass_conversion(cities,temp_path + region_name,"pop.shp",query)
else:
continue
Solved! Go to Solution.
if the tuple is singular what about slicing it
field = 'a'
top_cities = (10,)
query = "\"{0}\" == {1}".format(field,top_cities)
query
'"a" == (10,)' # wrong
query = "\"{0}\" == {1}".format(field,top_cities[0])
query
'"a" == 10' # right??
To avoid using escape characters, I normally use the arcpy.AddFieldDelimiters to take care of the field delimiters based on the type of data source:
datasource = r'C:\GeoNet\GW1\rectangles_v01.shp'
fld_name = 'MyField'
fld_where = arcpy.AddFieldDelimiters(datasource, fld_name)
print fld_where
# "MyField"
When you create the top cities this is a list:
lst_values = [10, 14, 7, 11, 12, 9]
top_cities = sorted(lst_values)[-4:]
print type(top_cities), top_cities
# <type 'list'> [10, 11, 12, 14]
To separate the list of values with commas you could use join (but this requires the values to be string to I used a list comprehension for that:
values = ', '.join([str(a) for a in top_cities])
print values
# 10, 11, 12, 14
To create the final where clause you can simply use this:
query = '{0} IN ({1})'.format(fld_where, values)
print query
# "MyField" IN (10, 11, 12, 14)
In case your values would be strings (just as an example) this could be done like this:
values = "', '".join(top_cities)
print values
# a', 'b', 'c', 'd
And the query would be formed like this:
query = "{0} IN ('{1}')".format(fld_where, values)
print query
# "MyField" IN ('a', 'b', 'c', 'd')
This returns "Pop_MAX" IN ([328585]) as above and I still get the SQL error.