简体   繁体   中英

Match data in SQL Server database using multiple and varying columns

We have a database table consisting of 6 "header" criteria and we need to match any combination of these columns to retrieve the detail data.

We wont know which of the criteria the underlying database will have as each of the 8 header columns are optional.

Using example data :-

+------------+-----------+-----------+-----+---------+--------------+--------+
| First Name | Last Name | Home Town | Age |  Gender |    Skill     | Salary |
+------------+-----------+-----------+-----+---------+--------------+--------+
| James      | Smith     | New York  | 30  | Male    | Train Driver |  30000 |
| Pete       | Jones     | ?         | 30  | Male    | ?            |  35000 |
| ?          | Smith     | New York  | ?   | Male    | ?            |  75000 |
| ?          | ?         | ?         | 30  | ?       | ?            |  30000 |
+------------+-----------+-----------+-----+---------+--------------+--------+

When we want to find salary we might specify :-

First Name = James
Last Name = Smith
Home Town = New York
Age = 30
Gender = Male
Skill = Train Driver

Using this criteria we would expect to get the 1st, 3rd and 4th row returned.

Is there a slick way of doing this apart from iteratively working through the criteria with all the different combinations?!

Many thanks in advance.

In mysql I would use IFNULL() (I think there is an equivalent NVL() method in sql server)

Eg

in your where query:

where IFNULL(row.FirstName, "James") == "James" and IFNULL(row.LastName, "Smith") and ..

Even better would be to use OR (ie check firstnames match or row.firstname is null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM