1

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
>>> 
Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Jul 29, 2019 at 18:35
0

1 Answer 1

2

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)
answered Jul 29, 2019 at 19:06
3
  • 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 python Commented 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. Commented Jul 29, 2019 at 20:11
  • the single quotes did the trick! Thanks for all your help :) Commented Jul 29, 2019 at 20:17

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.