Check table value and featureclass name

973
2
12-10-2020 01:15 PM
yalcinsahin
New Contributor

Hi,

 i want to make a model, with model builder from arcmap. but i must make a script for my step;

i have a table and a feature class(inputdata). there are fields, named "FEATURENAME" and "FIELDNAME"  field. i want to check both my table's "FEATURENAMES" and my featureclass's own name then if they equal gave me "exist" value, if they arent equal, it gives me "no exist" value. 

and after this step, "exist" value i will add (matched) row's "FIELDNAME" field in my featureclass with my model. (i will make this step with "AddField" tool.

Thnks a lot for your ans.

0 Kudos
2 Replies
DavidPike
MVP Frequent Contributor
0 Kudos
RandyBurton
MVP Alum

If I understand your project goal correctly, that you want to see if a feature class' name is in a data table, and if so, return the associated field name for that table, then the following script may serve as a starting point.

import arcpy

fc = arcpy.GetParameter(0)   # input feature class : feature layer, input
tbl = arcpy.GetParameter(1)  # input data table: table, input
# FieldName : Parameter(2)   # derived, output, string

fc_desc = arcpy.Describe(fc)
arcpy.AddMessage("Feature type: {}".format(fc_desc.dataType)) # 'FeatureClass','FeatureLayer'
arcpy.AddMessage("Feature name: {}".format(fc_desc.name))
arcpy.AddMessage("Feature catalog path: {}".format(fc_desc.catalogPath))

tbl_desc = arcpy.Describe(tbl)
arcpy.AddMessage("Table type: {}".format(tbl_desc.dataType)) # 'Table'
arcpy.AddMessage("Table name: {}".format(tbl_desc.name))
arcpy.AddMessage("Table catalog path: {}".format(tbl_desc.catalogPath))

# may wish to validate that table has fields 'FEATURENAME' and 'FIELDNAME'

where = "FEATURENAME = '{}'".format(fc_desc.name)
arcpy.AddMessage("Where clause: {}".format(where))

cursor = arcpy.da.SearchCursor(tbl_desc.catalogPath,['FIELDNAME'], where)
if any(cursor):
    fieldname = cursor[0]
else:
    fieldname = '' # empty string

del cursor
arcpy.SetParameterAsText(2, fieldname)
    
arcpy.AddMessage("Fieldname: {}".format(fieldname if len(fieldname) else '* FIELD NOT FOUND *'))

The script uses a number of AddMessage lines for debugging.  It does provide an idea for the  general flow.

In actual use, I would probably have most of the work done in the ToolValidator section where the parameters can be checked more thoroughly before the script tool completes.  One check the validator would make is to verify that the data table has the proper fields.  Another check could determine that the feature's name is in the data table.

If you plan to add a field to the feature, the tool could also be set to verify that the feature does not already contain the field.

0 Kudos