简体   繁体   中英

SqlQuerySpec parameterized query returns no results

I'm not sure whether it is an emulator issue or not but i have a really simple query

 var collectionUri = UriFactory.CreateDocumentCollectionUri(Constants.CosmosDbName, CollectionName);
            var spec = new SqlQuerySpec()
            {
                QueryText = "SELECT * FROM Users u WHERE u.firstName = @firstname",
                Parameters = new SqlParameterCollection
                {
                    new SqlParameter{
                        Name = "@firstname",
                        Value = value
                    }
                }
            };

            var query = client.CreateDocumentQuery<User>(collectionUri, spec);
            var users = await query.ToListAsync();  

the parametrized query returns no results ie 0 users while the same plain query below retuns 1 user that matches the WHERE condition:

            spec.Parameters.Clear();
            spec.QueryText = $"SELECT * FROM Users u WHERE u.firstName = '{value}'";
            query = client.CreateDocumentQuery<User>(collectionUri, spec);
            users = await query.ToListAsync();    // returns 1 user

do I need somehow explicitly enable parameterized queries or am I doing something wrong above with a parameterized query?

According to the Syntax, your query should be like this,

        SqlQuerySpec sqlQuerySpec = new SqlQuerySpec
        {
            QueryText = @"SELECT *
                        FROM    Users  u
                        WHERE   u.u.firstName = @firstname",
            Parameters = new SqlParameterCollection
            {
                new SqlParameter("@firstname", value)
            }
        };

The issue is a kind of var pitfall

the SqlParameter value was taken from an Azure function HttpRequest request:

var value = req.Query["firstname"]; 

which is

Microsoft.Extensions.Primitives.StringValues value = req.Query["firstname"];

When SqlParameter is created with value of StringValues type it makes slightly different query:

SELECT * FROM Users u WHERE u.firstName = ['Dima']

the brackets ['Dima'] here are excess

the correct query must be without brackets

SELECT * FROM Users u WHERE u.firstName = 'Dima'

so to fix the parameterized query the parameter value should be a string

new SqlParameter("@firstname",value.ToString())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM