简体   繁体   English

在sql server中搜索数字或字符串值作为通配符

[英]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 .如果用户输入一个数值,即 Staffid,则wildcard应用于员工table的 Staffid 列。
  2. If the user enters a string value ie staffname then wildcard to be applied on the staffname column of staff table .如果用户输入字符串值,即员工姓名,则wildcard将应用于员工table的员工姓名列。

how to implement the above scenario is sql server?.上面的场景是如何实现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.正如我所提到的,更好的方法是使用 2 个参数和分支搜索,具体取决于哪个被填充或执行一个查询。 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.这可以理解为:如果@pStuffID列中不包含除数字搜索之外的符号,或者如果它在Name列中不包含除字符搜索之外的符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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