简体   繁体   中英

SQL CASE isNumeric with multiple values?

I have an instance where sometimes we aren't sure to filter by the name text or the name id. I've solved this with a case statement and isnumeric . For example, we have both the id and name values but we're not sure which column is being asked to filter. rtresource.id is numeric, and in this case we have the value '183' to work with. If rtresource.rname (varchar) is trying to filter, then we have the rname for that id 'Jane Thompson'.

So the filter is either

rtresource.id=183

Or

rtresource.rname='Jane Thompson'

Instead becomes

rtresource.rname in (CASE IsNumeric(rtresource.rname) WHEN 1 then '183' else 'Jane Thompson' End) 

This works awesome. The issue is having more than one set of id/rname being passed. Typically, we would ask either rtresource.id in (183, 23) or rtresource.rname in ('Jane Thompson','John Doe') . How can I solve this with a case statement?

rtresource.rname in (CASE IsNumeric(rtresource.rname) WHEN 1 then ('183','23') else ('Jane Thompson','John Doe') End)

Above complains over the commas between values. I've also tried:

rtresource.rname in (CASE IsNumeric(rtresource.rname) WHEN 1 then ('183'+','+'23') else ('Jane Thompson'+','+'John Doe') End)

Which doesn't work either. Ideas? Thanks for any help in advance.

You have to repeat the case for every value in the list:

where rtresource.rname in (
  CASE IsNumeric(rtresource.rname) WHEN 1 then '183' else 'Jane Thompson' End,
  CASE IsNumeric(rtresource.rname) WHEN 1 then '23' else 'John Doe' End
)

or since the values don't intersect, just:

where rtresource.rname in (183, 23, 'Jane Thompson', 'John Doe')

which would perform much better as it will use an index (if any) of the column, and is easier to code, understand and scale.

Figured it out. Skip the case and instead:

(IsNumeric(rtresource.rname) = 1 and rtresource.rname in ('183','23')) or (IsNumeric(rtresource.rname) != 1 and rtresource.rname in ('Jane Thompson','John Doe'))

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