I have a list WRL_ID = ['NW-E8-105151', 'NW-E8-105138']
and I am trying to search these values in a field called ID
.
If the value exist, print 'It's in SDE', if not, print 'Not in SDE'.
Right now the first value NW-E8-105151
is in SDE and the second value NW-E8-105138
is not. When I try to run the script below, it prints out both are in SDE. What am I missing?
Fieldname = "ID"
flag = False
qry = """ID IN {0}""".format(str(tuple(WRL_ID)))
with arcpy.da.SearchCursor(AR_Master, Fieldname, qry) as theseRows:
for row in theseRows:
flag = True
print "It's in SDE"
if not flag:
print "Not in SDE"
>>>
['NW-E8-105151', 'NW-E8-105138']
It's in SDE
It's in SDE
>>>
1 Answer 1
Your script is printing that both values are in the SDE because your query is always returning at least one feature (and consequently one row) and thus your flag is always True
.
Check the following function to check if exists in a table or not:
def value_exists(fc, field, where_clause):
with arcpy.da.SearchCursor(fc, field, where_clause) as cursor:
try:
next(cursor)
return True
except StopIteration:
return False
What this function does is try to get the first row of the cursor. If the cursor does not return any rows (because there are no features that satisfy the query) it raises a StopIteration
error when next(cursor)
is called.
Then you can call this function for each one of the values in your list, by bulding dynamically the query:
for val in WRL_ID:
qry = "ID = '{}'".format(val)
val_in_sde = value_exists(AR_Master, Fieldname, qry)
-
Thanks for your help, but when I try this it said RuntimeError: Attribute column not found [42S22:[Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'NW'.] [SpatialDB.SDEADMIN.Asset_Rights_Master_Polygon_1]. Why did it turn the first 2 character of the list into the field name? I try printing our 'qry' and it looks right "ID = NW-E8-105151". Sorry still a newbie in pythonuser97941– user979412019年07月29日 20:07:14 +00:00Commented Jul 29, 2019 at 20:07
-
Wierd. Are you passing the right value for
Fieldname
? Also, try enclosing the value in the query with single quotes like this:qry = "ID = '{}'".format(val)
and let me know if it works.Marcelo Villa– Marcelo Villa2019年07月29日 20:11:53 +00:00Commented Jul 29, 2019 at 20:11 -
the single quotes did the trick! Thanks for all your help :)user97941– user979412019年07月29日 20:17:31 +00:00Commented Jul 29, 2019 at 20:17