Select to view content in your preferred language

SQL Statement Problems When Transferring My Code to Arc as a Script

792
4
Jump to solution
07-01-2013 12:08 PM
ScottBarron
Regular Contributor
I'm trying to make a tool for end users to use in Arc, and I want to make the SQL statement a variable. So far I have this:

Where_Clause= """"GRIDCODE"=6""" arcpy.SelectLayerByAttribute_management ("Quakesim_lyr", "NEW_SELECTION", Where_Clause)


which works fine in Python, but when I run it as a tool in arc, I'm getting Invalid Statement errors, even though the statement is the same.

Any advice? Bonus points if you can help me with the next step, which would be to replace the '6' with a variable that I could change.
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
ScottBarron
Regular Contributor
Of course, it was even more simple than that. The reason it wasn't working is because I chose "String" for my input instead of "SQL statement" Once I changed the parameter it worked perfectly.
Thanks anyway!

View solution in original post

0 Kudos
4 Replies
ChrisPedrezuela
Frequent Contributor
try,

inputVariable =  arcpy.GetParameterAsText(0)
arcpy.SelectLayerByAttribute_management ("Quakesim_lyr", "NEW_SELECTION", where_clause='"GRIDCODE"={0}'.format(inputVariable))
0 Kudos
ScottBarron
Regular Contributor
Of course, it was even more simple than that. The reason it wasn't working is because I chose "String" for my input instead of "SQL statement" Once I changed the parameter it worked perfectly.
Thanks anyway!
0 Kudos
ChrisPedrezuela
Frequent Contributor
Yup your right. The difference of the code I put above is that you can make an input variable part of your where_clause which you said was your next step.:o

Of course, it was even more simple than that. The reason it wasn't working is because I chose "String" for my input instead of "SQL statement" Once I changed the parameter it worked perfectly.
Thanks anyway!
0 Kudos
RhettZufelt
MVP Notable Contributor
I'm trying to make a tool for end users to use in Arc, and I want to make the SQL statement a variable. So far I have this: 

Where_Clause= """"GRIDCODE"=6"""
yourvar = 6

Where_Clause= arcpy.AddFieldDelimiters(Quakesim_lyr,"GRIDCODE") + " = â??" + yourvar + "â??"  # this if GRIDCODE is actually string


Where_Clause= arcpy.AddFieldDelimiters(Quakesim_lyr,"GRIDCODE") + " = "  yourvar  ## this if GRIDCODE is numeric


arcpy.SelectLayerByAttribute_management ("Quakesim_lyr", "NEW_SELECTION", Where_Clause)


which works fine in Python, but when I run it as a tool in arc, I'm getting Invalid Statement errors, even though the statement is the same.  

Any advice? Bonus points if you can help me with the next step, which would be to replace the '6' with a variable that I could change.


Could try something like above to code your where clause using a variable. though thanos_cp78's is more elegant. Guess I need to learn how to use the .format stuff....

R_
0 Kudos