Thursday 22 September 2016

arcpy - Generating SQL expression from multivalue pick list in ArcGIS tool


I have created a script tool that allows users to select a single value from a pick list, which gets inserted into a query expression.


The pertinent part of my code is pretty simple:


Input = arcpy.GetParameterAsText(0)


arcpy.MakeQueryTable_management(inTable, "TabTemp", "", "", "", "FieldName = " + str(Input))

So if a user selects as input "Item1", then the resulting SQL expression is FieldName = Item1.


I am hoping to make the input a multi-value pick list, so that a user could potentially select one, or multiple values as Input. For example, if the user selects Item1, Item2 and Item3, then the SQL expression should look like:


FieldName = Item1 OR FieldName = Item2 OR Field Name = Item 3


I'm not quite sure how to get started with the python code to do this. Can anybody offer suggestions for creating the necessary code to compile the SQL expression from an unknown number of values obtained from a multi-value pick list?



Answer



If you are aiming for an interface such as below:


Example Interface



Then you need to set the parameter as shown below:


Setting parameter properties


In the Filter property set it as Value List and type in all the possible values.


The actual code to create the query would be:


import arcpy
import string

def main():
x = arcpy.GetParameterAsText(0)
vals = string.split(x,";")

whereClause = "FieldName IN (" + string.join(vals,",") + ")"
arcpy.AddMessage(whereClause)

if __name__ == '__main__':
main()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...