简体   繁体   中英

SQL text search on any record field

I´m building a grid system and I need to search for a text occurrence on ANY field or my record - even being strings, timestamp and numbers.

Something like:

SELECT * FROM MYTABLE WHERE ANY_FIELD CONTAINS ('MyText')

If not, what would be the way to go for a solution ?

PS: I´m using mySql as database, but I will have to support that on Oracle and SqlServer as well.

Thanks for help.

I don't know MySQL well enough to really offer any solution on that end, but since you mentioned you'll need to use this searching method on SQL Server as well, I can offer a solution for that side.

In SQL Server, you can search all columns at the same time by invoking some XML and XQuery magic:

Declare @Value nvarchar(max)

Set @Value = 'YourSearchTextHere'

;With xml As
(
    Select  T2.Xml, T1.SomePrimaryId
    From    YourTable as T1
    Cross Apply 
    (
        Select T1.* for xml path(''), type
    ) as T2(Xml)
)
Select  c.*
From    xml x
Join    YourTable c on c.SomePrimaryId = x.SomePrimaryId
Where   x.xml.value('contains((.),sql:variable("@Value"))','bit') = 1

Here's a working demo on SQLFiddle .

Essentially, it's converting every row in the table into XML with the columns as separate nodes, then searching that XML for any node whose value contains the value you're searching for.

SELECT * FROM MYTABLE WHERE MATCH (ANY_FIELD_1, ANY_FIELD_2) AGAINST ('MyText' IN BOOLEAN MODE)

You can also have a look on Boolean Full-Text Searches . Here are few more operators which you might need or like to implement in the code for example

+ stands for AND

- stands for NOT

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