Saturday, 8 September 2018

arcpy - MultiValue-String to SQL Expressions


I am aware that problems like mine exist (example) but I think, this is slightly different.


I want to use MultiValue to let the user choose various inputs at the same time. The problem is, that it's only possible to use MultiValue in combination with String and not, how I would need it, as SQL.


Because I'am trying to create a toolbox, these are my properties (and on the right side my MultiValue-Field in the Toolbox:


Toolbox-Properties


I did it like this:


multival = arcpy.GetParameterAsText(1)
vals = string.split(multival, ";")

where_clause = string.join(vals, "+")

My problem is, that my output now has quotation marks and is not combined to one big SQL-expression.


The expression I am aiming for would look like this:


"Name = 'Store_1' OR Name = 'Store_2' OR Name = 'Store_5' OR Name = 'Store_8'"

But right now it looks like this:


'Name = 'Store_2''+'OR Name = 'Store_3''+'OR Name = 'Store_4''+'OR Name = 'Store_5''

Is there a way to have the outputs without quotations marks and added to one expression?




Answer



Your comment on using the IN is a good way to go; makes the code much simpler.


multival = arcpy.GetParameterAsText(1)  # 'Store_1;Store_2;Store_3'
vals = multival.split(";")

where_stub = """"NAME" IN ({})"""
stores = ','.join(["'{}'".format(x) for x in vals])
where = where_stub.format(stores)

You can combine some of those lines, if you'd like.



EDIT: I just noticed your screenshot has the "OR NAME =" in there. There's no need. Just have the list of values. For example:



  • Store_1

  • Store_2

  • etc


No comments:

Post a Comment