如果一个是空的,则在多列中搜索sql,然后从另一列中获取

时间:2015-02-02 09:53:56

标签: c# sql sql-server sql-server-2008

WITH FilteredClient AS
(
    SELECT 
        Client.ClientId, Client.PersonId, Client.ClientCompanyId, 
        Client.ClientCategoryId, Client.IsImported, Client.IsModified, 
        Client.StatusId, Client.ClientTypeId, Client.LeadSourceId, 
        Person.Company, Person.FirstName, Person.MiddleName, 
        Person.LastName, Person.AddressLine1, Person.AddressLine2, 
        Person.AddressLine3, Person.City, Person.State, 
        Person.Country, Person.Zip, 
        Person.HomePhone, Person.WorkPhone, Person.CellPhone, 
        Person.Fax, Person.EmailId, Person.Website, 
        ClientStatus.ClientStatusName, 
        ClientCategory.ClientCategoryName, 
        ClientType.ClientTypeName, LeadSource.LeadSourceName,
        [User].Username, Client.AddedBy, [User].UserId
    FROM 
        Client 
    INNER JOIN
        ClientCategory ON Client.ClientCategoryId = ClientCategory.ClientCategoryId 
    INNER JOIN
        Person ON Client.PersonId = Person.PersonId
    INNER JOIN 
        ClientType ON Client.ClientTypeId = ClientType.ClientTypeId 
    INNER JOIN
        ClientStatus on Client.StatusId = ClientStatus.ClientStatusId  
    INNER JOIN
        LeadSource on Client.LeadSourceId = LeadSource.LeadSourceId 
    INNER JOIN
        [User] ON [User].UserId = Client.AddedBy
    WHERE     
        (Client.CompanyId = 1
        AND ClientCategory.ClientCategoryName LIKE ('%%')
        AND ClientType.ClientTypeName LIKE ('%%')
        AND ClientStatus.ClientStatusName LIKE ('%%')
        AND LeadSource.LeadSourceName LIKE ('%%')
        AND (Person.FirstName + '' + Person.MiddleName + '' + Person.LastName) LIKE ('%Tom%')
        AND person.Company LIKE ('%Tom%'))
)
SELECT
    ClientId, PersonId, ClientCompanyId, ClientCategoryId,
    IsImported, IsModified, StatusId, ClientTypeId, LeadSourceId, 
    Company, FirstName, MiddleName, LastName, 
    AddressLine1, AddressLine2, AddressLine3, 
    City, [State], Country, Zip, 
    HomePhone, WorkPhone, CellPhone, Fax, EmailId, Website, 
    ClientStatusName, ClientCategoryName, ClientTypeName,
    LeadSourceId, LeadSourceName, Username, AddedBy, UserId
FROM 
    FilteredClient

现在我根据ClientName进行搜索(客户名称包括CompanyName和person的名字)。两者都在Person表格中有单独的列。

我将文本放在文本框中,然后单击搜索,然后textbox的值转到company.person和person.firstname。

现在我希望搜索结果来自两个列,但是如果在公司名称中找到匹配项,那么它会选择公司名称和相关人名,但如果我将人名放在文本框中,那么如果公司列的结果是0,那么它是没有亲自搜索第一个名字

如果我的情况有任何错误,请告诉我

请帮帮我

2 个答案:

答案 0 :(得分:0)

您正在使用AND子句,其中条件是根据您的要求的错误。您应该使用OR子句而不是AND,所以用以下

替换您的查询
AND ((Person.FirstName +''+Person.MiddleName +''+Person.LastName) like ('%Tom%')
OR person.Company like('%Tom%'))

答案 1 :(得分:0)

看看这个答案。这可以帮助您调整算法并调整您的要求: This Link