Over a million developers have joined DZone.
Platinum Partner

SQL Server Compact Code Snippet of the Week #17 : using wildcards with a parameterized query

The Performance Zone is brought to you in partnership with AppDynamics. Discover five of the top performance metrics to capture to assess the health of your enterprise Java application.

This “week”’s code snippet simply demonstrates how to use a parameterized query with LIKE and a search string containing wildcards. The simple solution is basically to add the wildcard character (% or ?) directly to the search string.

public static List<string> GetCompletionList(string prefixText = "%orch%")
        {
            //TODO Add error handling
            List<string> Names = new List<string>();
            using (SqlCeConnection con = new SqlCeConnection(@"Data Source=C:\projects\Chinook\Chinook40.sdf"))
            {
                con.Open();
                using (SqlCeCommand cmd = new SqlCeCommand("SELECT Name FROM Artist WHERE Name LIKE @Name", con))
                {
                    cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 120).Value = prefixText;
                    using (SqlCeDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Names.Add(reader[0].ToString());                            
                        }
                    }
                }
            }
            return Names;
        }

 

The Performance Zone is brought to you in partnership with AppDynamics.  Learn the essentials of APM and how to implement best practices of application performance, better understand what it means to capture, analyze, and react to performance problems as they arise, and more specifically with .NET applications. 

Topics:

Published at DZone with permission of Erik Ejlskov Jensen , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}