Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized LIKE clause in SQL statement using Dapper

Tags:

sql

dapper

I want to perform the following query using Dapper, which currently doesn't return expected results (I think it must be treating the @pName param as literal text within the single quotes?):

var q = "SELECT * FROM Users WHERE Name LIKE '@pName%'";

@pName is the param I assign a value to upon executing the query.

Things work if I just build the SQL like:

var q = "SELECT * FROM Users WHERE Name LIKE '" + name + "%'";

.. but I would prefer to use a param if possible.

I am executing the query using the following code:

o = _cn.Query<User>(q, new { pName = new DbString { Value = name, IsFixedLength = false, Length = 25, IsAnsi = true } }).ToList();

How do I got about this using Dapper?

like image 660
marcusstarnes Avatar asked Sep 22 '11 08:09

marcusstarnes


People also ask

How do you pass multiple parameters in dapper query?

To use the dynamic parameters you have to set each parameter in the stored procedure, so you will have to loop through the list and add each property to the coresponding parameter.

How do I write a parameterized query in SQL?

Declare statements start with the keyword DECLARE , followed by the name of the parameter (starting with a question mark) followed by the type of the parameter and an optional default value. The default value must be a literal value, either STRING , NUMERIC , BOOLEAN , DATE , or TIME .

What is a parameterized query in a SQL statement?

Parameterized SQL queries allow you to place parameters in an SQL query instead of a constant value. A parameter takes a value only when the query is executed, which allows the query to be reused with different values and for different purposes.


1 Answers

SELECT * FROM Users WHERE Name LIKE @pName + '%'
like image 92
Marcelo Cantos Avatar answered Nov 10 '22 01:11

Marcelo Cantos