How do I use the SQL WHERE IN construct with PetaPoco?
Asked Answered
U

5

36

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

Ungotten answered 4/8, 2011 at 15:32 Comment(0)
V
61

This will work except you can't use the @0 (ordinal) syntax. You must use named parameters, otherwise it thinks they are individual parameters.

var tagsToFind = new string[] { "SqlServer", "IIS" };
var sql = PetaPoco.Sql.Builder.Select("*").From("Tags").Where("Name in (@tags)", new { tags = tagsToFind });
var result = db.Query<Tag>(sql);

This will result in

select * from Tags where name in (@0, @1);
@0 = SqlServer, @1 = IIS
Vorster answered 5/8, 2011 at 14:4 Comment(4)
Great, that helped me with using multiple parameters in general with PetaPoco, thanks!Ungotten
When I tried that with an integer array, it simply left the clause as "field in (@0)" Instead, I performed a string.Join(",", integerArray) as the parameter. This seemed more efficient anyway, as the PetaPoco ParametersHelper class iterates the enumerable element.Wallache
Holy smokes! That's some outside-the-box thinkingTitanomachy
Version 4.01 of nPoco requires using .WhereSql() instead of .Where().Malissa
D
18

Posting this for future seekers. This works.

    public IEnumerable<Invoice> GetInvoicesByStatus(List<string> statuses)
    {
        return _database.Fetch<Invoice>(@"
            select *
            from Invoices                   
            where Status IN (@statuses)",
            new { statuses });
    }
Decemvirate answered 14/8, 2013 at 23:10 Comment(0)
L
9

If you want to use array class with Petapoco you can use this

string[] array = new string[] {"Name1","Name2" };

var foo = BasicRepository<Personnel>.Fetch("WHERE PersonnelId IN (@0)", array.ToArray());
Longstanding answered 8/3, 2016 at 12:59 Comment(1)
That .ToArray() fixed the problem I was having. itemLists = rep.Find("WHERE ItemId IN (@0)", items.ToArray()).ToList() thanks.Manoeuvre
T
1

Here is an another sample:

program.cs:

public static void Main(string[] args)
{
    using (var db = new PetaPoco.Database("Northwind"))
    {
        var sql = "Select * from customers where Country in (@Countries)";
        var countries = new { @Countries = new string[] { "USA", "Mexico" } };
        var customers = db.Query<Customer>(sql, countries);
        foreach (var customer in customers)
        {
            Console.WriteLine("{0} - {1} from {2}", customer.CustomerID, customer.CompanyName, customer.Country);
        }
    }
}

customer.cs:

public class Customer
{
    public string CustomerID { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string ContactTitle { get; set; }
    public string Country { get; set; }
    public string Fax { get; set; }
    public string Phone { get; set; }
    public string PostalCode { get; set; }
    public string Region { get; set; }
}

App.config: (Connectionstring uses localdb connectionstring, so you might change it.)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <connectionStrings>
    <clear/>
    <add name="Northwind"
         connectionString="Data Source=(localdb)\v11.0;Initial Catalog=northwind;Integrated Security=True;"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>
Transport answered 4/5, 2014 at 16:48 Comment(0)
E
-2

Maybe, it's not a good way setting too many params in sql, the max params limit is 2100.

@Murat

string[] array = new string[] {"Name1","Name2" };
var foo = BasicRepository<Personnel>.Fetch("WHERE PersonnelId IN > (@0)", array.ToArray());

Constructing stander SQL in string, and check the LAST excute-sql, alway match your need.

var userIDs = from user in UserList select user.UserID;
db.Delete<User>("where UserID in (" + string.Join(",", userIDs) + ")");
Edwinaedwine answered 31/8, 2017 at 8:32 Comment(2)
Actually DON'T do this. You have just introduced SQL Injection vulnerability by bypassing the SQL Parameters.Amass
Use a Table Valued Parameter instead. Then you can pass the Datatable of IDs and not worry about hitting the parameters limit.Norby

© 2022 - 2024 — McMap. All rights reserved.