I have a database table named Tags (Id, Name) from which I would like to select the ones where the name matches a name in a list. In SQL I would use something like:
Select * from Tags Where Name In ('Name1', 'Name2', 'xxx...)
But now using PetaPoco in an ASP.Net MVC3 project I'm stuck figuring out how to do it properly. So far I've tried:
var tagsToFind = new string[] { "SqlServer", "IIS" };
var sql = PetaPoco.Sql.Builder.Select("*").From("Tags").Where("Name in (@0)", tagsToFind);
var result = db.Query<Tag>(sql);
Which results in the following SQL, where only the first name in my list of tagsToFind is used to match the table data as opposed to all of them.
SELECT * FROM Tags WHERE (Name in (@0)) -> @0 [String] = "SqlServer"
It's a little frustrating, knowing this probably isn't so hard.. any help is appreciated!
Update: I found out that it can be done in another way
var sql = PetaPoco.Sql.Builder.Append("Select * from tags Where Name IN (@0", tagNames[0]);
foreach (string tagName in tagNames.Where(x => x != tagNames[0])) {
sql.Append(", @0", tagName);
}
sql.Append(")");
var result = db.Query<Tag>(sql)
which gets me what I want while using sqlparameters. So I guess it's good enough for now, although not super pretty.
/Mike
Posting this for future seekers. This works.
If you want to use array class with Petapoco you can use this
Here is an another sample:
program.cs:
customer.cs:
App.config: (Connectionstring uses localdb connectionstring, so you might change it.)
Maybe, it's not a good way setting too many params in sql, the max params limit is 2100.
Constructing stander SQL in string, and check the LAST excute-sql, alway match your need.
This will work except you can't use the @0 (ordinal) syntax. You must use named parameters, otherwise it thinks they are individual parameters.
This will result in