azureazure-table-storageazure-tablequery

How to escape characters in Azure Table queries?


I want to query for rows where a column named message starts with: metric="foo"

I tried encoding = and " with percentage and hex codes but it did not work.

Microsoft documentations says special characters must be encoded but does not tell how: https://learn.microsoft.com/en-us/rest/api/storageservices/querying-tables-and-entities#query-string-encoding

What should the query look like when value being compared contains special characters?


Solution

  • If you're using azure sdk, then the sdk already did the tricky for you.

    In my test, I'm using the latest azure table storage sdk Microsoft.Azure.Cosmos.Table, version 1.0.4.

    The test code:

        static void Main(string[] args)
        {
            string connstr = "xxxx";
            var storageAccount = CloudStorageAccount.Parse(connstr);
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("myCustomer123");
    
            TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>();
    
            string myfilter = TableQuery.CombineFilters(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "ivan"),
                                      TableOperators.And,
                                      //for metric="foo", like below.                                      
                                      TableQuery.GenerateFilterCondition("PhoneNumber", QueryComparisons.Equal, "metric=\"foo\"")
                                      );
    
            query.FilterString = myfilter;
    
            var items = table.ExecuteQuery(query);
    
            foreach (var item in items)
            {
                Console.WriteLine(item.RowKey);
                Console.WriteLine(item.PhoneNumber);
            }
    
           Console.WriteLine("*****end******");
           Console.ReadLine();
    
        }
    

    Test result:

    enter image description here