如何将 SQL WHERE IN 构造与 PetaPoco 结合使用?

发布于 2024-11-27 17:02:03 字数 1072 浏览 4 评论 0原文

我有一个名为 Tags (Id, Name) 的数据库表,我想从中选择名称与列表中的名称匹配的表。在 SQL 中,我会使用类似的东西:

Select * from Tags Where Name In ('Name1', 'Name2', 'xxx...)

但现在在 ASP.Net MVC3 项目中使用 PetaPoco,我一直在想如何正确地做到这一点。到目前为止,我已经尝试过:

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);

这会产生以下 SQL,其中 仅使用 tagToFind 列表中的第一个 名称来匹配表数据,而不是所有数据。

SELECT * FROM Tags WHERE (Name in (@0)) -> @0 [String] = "SqlServer"

有点令人沮丧,知道这可能并不难......任何帮助都是值得赞赏的!

更新: 我发现可以用另一种方式来完成,

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)

这可以让我在使用 sqlparameters 时得到我想要的东西。所以我想现在已经足够好了,尽管不是非常漂亮。

/麦克风

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

庆幸我还是我 2024-12-04 17:02:03

除非您不能使用@0(序数)语法,否则这将有效。您必须使用命名参数,否则它认为它们是单独的参数。

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);

这将导致

select * from Tags where name in (@0, @1);
@0 = SqlServer, @1 = IIS

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
一杆小烟枪 2024-12-04 17:02:03

将此发布给未来的寻求者。这有效。

    public IEnumerable<Invoice> GetInvoicesByStatus(List<string> statuses)
    {
        return _database.Fetch<Invoice>(@"
            select *
            from Invoices                   
            where Status IN (@statuses)",
            new { statuses });
    }

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 });
    }
梦毁影碎の 2024-12-04 17:02:03

如果你想在 Petapoco 中使用数组类,你可以使用这个

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

var foo = BasicRepository<Personnel>.Fetch("WHERE PersonnelId IN (@0)", array.ToArray());

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());
爱*していゐ 2024-12-04 17:02:03

这是另一个示例:

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:
(连接字符串使用 localdb 连接字符串,因此您可以更改它。)

<?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>

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>
不一样的天空 2024-12-04 17:02:03

也许,在sql中设置太多参数并不是一个好方法,最大参数限制为 2100

@穆拉特

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

在字符串中构造标准SQL,并检查最后的执行sql,始终符合您的需要。

var userIDs = from user in UserList select user.UserID;
db.Delete<User>("where UserID in (" + string.Join(",", userIDs) + ")");

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) + ")");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文