C#LIKE查询不起作用

时间:2013-07-08 13:18:18

标签: sql nhibernate

有人可以帮帮我吗?我通常不会在C#工作,所以我道歉。我有以下查询,但需要将store.Zip查找更改为LIKE而不是=。当我尝试将=更改为LIKE并在%之后添加{0}时,它会编译,但不会运行。数据库是Sql Server 2008:

public List<Store> DoesStoreExist(string customerNumber, string zipCode) {
    StringBuilder sb = new StringBuilder();
    sb.Append("SELECT id, Company, CustomerNumber, Name, Address, City, State, Zip, Phone, Latitude, Longitude, NumOfReferrals, IsNashville, PredsPromotionParticipant ");
    sb.Append("FROM dbo.Stores store ");
    sb.AppendFormat("WHERE store.CustomerNumber='{0}' ", customerNumber);
    sb.AppendFormat("AND store.Zip ='{0}' ", zipCode);
    sb.AppendFormat("AND store.Locator=1");

    IQuery query = NHibernateSession.CreateSQLQuery(sb.ToString());
    IList results = query.List();
    List<Store> stores = new List<Store>();
    foreach (object result in results) {
        object[] result_arr = result as object[];
        if (result_arr != null) stores.Add(Store.From(result_arr));
    }
    return stores;

}

即使只是将“=”更改为“LIKE”也会导致查询无法返回:

public List<Store> DoesStoreExist(string customerNumber, string zipCode) 
{        
        StringBuilder sb = new StringBuilder();
        sb.Append("SELECT id, Company, CustomerNumber, Name, Address, City, State, Zip, Phone, Latitude, Longitude, NumOfReferrals, IsNashville, PredsPromotionParticipant ");
        sb.Append("FROM dbo.Stores store ");
        sb.AppendFormat("WHERE store.CustomerNumber='{0}' ", customerNumber);
        sb.AppendFormat("AND store.Zip LIKE '{0}%' ", zipCode);
        sb.AppendFormat("AND store.Locator=1");

    IQuery query = NHibernateSession.CreateSQLQuery(sb.ToString());
    IList results = query.List();
    List<Store> stores = new List<Store>();
    foreach (object result in results) {
        object[] result_arr = result as object[];
        if (result_arr != null) stores.Add(Store.From(result_arr));
    }
    return stores;
}

当我直接对数据库运行以下内容时,它可以工作:

SELECT * FROM [StoreDB].[dbo].[Stores]WHERE Zip LIKE '33815%'

谢谢!

3 个答案:

答案 0 :(得分:0)

试试这个

    public List<Store> DoesStoreExist(string customerNumber, string zipCode)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("SELECT id, Company, CustomerNumber, Name, Address, City, State, Zip, Phone, Latitude, Longitude, NumOfReferrals, IsNashville, PredsPromotionParticipant ");
        sb.Append("FROM dbo.Stores store ");
        sb.AppendFormat("WHERE store.CustomerNumber ='{0}' ", customerNumber);
        sb.AppendFormat("AND store.Zip like '{0}%' ", zipCode);
        sb.AppendFormat("AND store.Locator=1");
    }

答案 1 :(得分:0)

这应该有效: sb.AppendFormat(&#34; AND store.Zip like&#39; {0}%&#39;&#34;,zipCode);

答案 2 :(得分:0)

如果超时,则需要增加命令超时。假设您的实体对象名为'db',请在执行c#代码中的查询之前执行此操作。

db.CommandTimeout = 300;

超时以秒为单位。