简体   繁体   中英

Search numeric or string value as wildcard in sql server

We have a requirement to implement search functionality in our webpage. The logic is as follows,

  1. If the user enters a numeric value ie staffid then wildcard to applied on the staffid column of staff table .
  2. If the user enters a string value ie staffname then wildcard to be applied on the staffname column of staff table .

how to implement the above scenario is sql server?.

Thanks for the help.

As I have mentioned the better way is to have 2 parameters and branch search depending on which is filled or do it one query. But if you insist this is how you can do this:

DECLARE @p VARCHAR(10) = 'jo'
--DECLARE @p VARCHAR(10) = '34'

DECLARE @t TABLE(StuffID INT, Name VARCHAR(100))
INSERT INTO @t VALUES
(1234, 'Michael Jordan'),
(7845, 'Scottie Pippen'),
(6541, 'Dennis Rodman'),
(1987, 'Phil Jackson')

SELECT * FROM @t
WHERE (@p NOT LIKE '%[^0-9]%' AND StuffID LIKE '%' + @p + '%') OR
      (@p NOT LIKE '%[^a-z]%' AND Name LIKE '%' + @p + '%')

This can be read as: if @p doesn't contain symbols other than digits search in StuffID column or if it doesn't contain symbols other than chars search in Name column.

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