Select to view content in your preferred language

cast a where statement

753
2
09-09-2011 12:37 PM
ChrisBradberry
Deactivated User
Hey,

I am using the make feature layer command with a user defined feature class and field.  The where statement is created with the field and value that the user defines.  The problem is that the field is sometimes a number and sometimes a text value.  So the quotes (or lack of them) in the where statement will crash the make feature layer command. 

I tried to use the cast or convert commands to convert the field to a string field so the where command will always have the same type of quotes.  I am not able to get the convert or cast to work.  Here are some samples of what I tried:
                        //string whereClause = "Cast(\"" + fieldname + "\" AS varchar) = '" + fieldval + "'";
                        //string whereClause = "\"Cast(" + fieldname + " AS varchar)\" = '" + fieldval + "'";
                        //string whereClause = "\"" + fieldname + "\" = '" + fieldval + "'";
                        //string whereClause = "\"Convert(varchar(500), '" + fieldname + "')\" = '" + fieldval + "'";
                        //string whereClause = "\"Convert(varchar, '" + fieldname + "')\" = '" + fieldval + "'";
                        //string whereClause = "Convert(varchar, \"" + fieldname + "\") = '" + fieldval + "'";
                        string whereClause = "Convert(varchar, " + fieldname + ") = '" + fieldval + "'";


Does anybody know how to use the convert or cast command, or a better way to accomplish this?

Thanks, Chris
0 Kudos
2 Replies
NeilClemmons
Honored Contributor
I would just look at the field type and format the query accordingly.  I haven't tested this but it would look something like this:

    Public Function GenerateQueryString(ByVal featureClass As IFeatureClass, ByVal fieldName As String, ByVal value As Object) As String
        Dim field As IField = featureClass.Fields.Field(featureClass.Fields.FindField(fieldName))
        Dim delimiter As String = String.Empty
        If field.Type = esriFieldType.esriFieldTypeString Then delimiter = "'"

        Dim queryString As String = String.Format("{0} = {1}{2}{1}", fieldName, delimiter, value)
        Return queryString
    End Function
0 Kudos
ChrisBradberry
Deactivated User
Thanks Neil,

That did the trick,

Chris
0 Kudos