2

I have several make query and feature class to feature class arcpy tools that create the necessary feature classes from my SQL queries. Is there a way to incorporate this into a for loop?

arcpy.MakeQueryLayer_management(input_database=db,
 out_layer_name ='test1lyr',
 query = test1,
 oid_fields = "test1id")
arcpy.FeatureClassToFeatureClass_conversion('test1lyr', scratchGDB, 'test1')
arcpy.MakeQueryLayer_management(input_database=db,
 out_layer_name ='test2lyr',
 query = test2,
 oid_fields = "test2id")
arcpy.FeatureClassToFeatureClass_conversion('test2lyr', scratchGDB, 'test2')
arcpy.MakeQueryLayer_management(input_database=db,
 out_layer_name ='test3lyr',
 query = test3,
 oid_fields = "test3id")
arcpy.FeatureClassToFeatureClass_conversion('test3lyr', scratchGDB, 'test3')
arcpy.MakeQueryLayer_management(input_database=db,
 out_layer_name ='test4lyr',
 query = test4,
 oid_fields = "test4id")
arcpy.FeatureClassToFeatureClass_conversion('test4lyr', scratchGDB, 'test4')
arcpy.MakeQueryLayer_management(input_database=db,
 out_layer_name ='test5lyr',
 query = test5,
 oid_fields = "test5id")
arcpy.FeatureClassToFeatureClass_conversion('test5lyr', scratchGDB, 'test5')
asked Nov 21, 2016 at 18:25

1 Answer 1

3

Sure.

# However these are defined
queries = [test1, test2, test3, test4, test5]
for i,query in enumerate(queries, 1):
 layer = arcpy.MakeQueryLayer_management(input_database=db,
 out_layer_name='test{}lyr'.format(i),
 query=query,
 oid_fields="test{}id".format(i))[0]
 arcpy.FeatureClassToFeatureClass_conversion(layer, scratchGDB, 'test{}'.format(i))

enumerate() removes the need for a counter and .format() with i ensures that no data will be overwritten.

answered Nov 21, 2016 at 18:50
2
  • That worked. One more question - I've updated my sql queries to have a unique name. From queries = [test1, test2, test3, test4, test5] to queries = [test90, test180, g_test30HIH, g_test90HIH, g_test180HIH]... Using the example above, how would I use .format to name my results test90ly rather than test1lyr, and g_test180HIHlry rather than test5lyr Etc.? Thanks! Commented Nov 21, 2016 at 20:22
  • @arzola, one way would be to change queries to a dictionary like {'name of layer1' : 'the query to use for 1', 'name of layer2' : 'query 2'} out_layer_name=key and query=value Commented Nov 21, 2016 at 21:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.