score:0

possible but from my point of view, it is not recommended. consider having 1000k of records of 100 of tables. slow performance you can do that by linq to sql by making a sp at database level and calling through entities. it will be much faster then the one you trying to achieve =)

score:0

late answer, but since i just had to come up with something for myself, here goes. i wrote the following to search all columns of all tables for a string match. this is related to a data forensics task that was given to me to find all occurences of a string match in a database weighing around 24gb. at this size, you can imagine using cursors or single threaded queries will be rather slow and searching the entire database would take ages. i wrote the following clr stored procedure to do the work for me server side and return results in xml, while forcing parallelization. it is impressively fast. a database-wide search on the standard adventureworks2017 database completes in less than 2 seconds. enjoy!

example usages:

using all available processors on the server:

exec [dbo].[searchalltables] @valuesearchterm = 'john michael'

limiting the server to 4 concurrent threads:

exec [dbo].[searchalltables] @valuesearchterm = 'john michael', @maxdegreeofparallelism = 4

using logical operators in search terms:

exec [dbo].[searchalltables] @valuesearchterm = '(john or michael) and not jack', @tablessearchterm = 'not contact'

limiting search to table names and/or column names containing some search terms:

exec [dbo].[searchalltables] @valuesearchterm = 'john michael', @tablessearchterm = 'person contact', @columnssearchterm = 'address name'

limiting search results to the first row of each table where the terms are found:

exec [dbo].[searchalltables] @valuesearchterm = 'john michael', @getonlyfirstrowpertable = 1

limiting the search to the schema only automatically returns only the first row for each table:

exec [dbo].[searchalltables] @tablessearchterm = 'person contact'

only return the search queries:

exec [dbo].[searchalltables] @valuesearchterm = 'john michael', @tablessearchterm = 'person contact', @onlyoutputqueries = 1

capturing results into temporary table and sorting:

create table #temp (result nvarchar(max));
insert into #temp
    exec [dbo].[searchalltables] @valuesearchterm = 'john';
select * from #temp order by result asc;
drop table #temp;

https://pastebin.com/rrtrt8zn

score:0

i ended up writing this little custom gem (finds all matching records given a search term):

namespace sqlservermetasearchscan
{
    using newtonsoft.json;
    using system;
    using system.collections.generic;
    using system.data;
    using system.data.sqlclient;
    using system.io;
    using system.linq;
    using system.security.cryptography;
    using system.text;
    using system.threading;
    using system.xml;

public class program
{
    #region ignition
    public static void main(string[] args)
    {
        // defaulting
        sqlconnection connection = null;

        try
        {               
            // questions
            colorconsole.print("sql connection string> ");
            string connectionstring = console.readline();
            colorconsole.print("search term (case ignored)> ");
            string searchterm = console.readline();
            colorconsole.print("skip databases (comma delimited)> ");
            list<string> skipdatabases = console.readline().split(',').where(item => item.trim() != string.empty).tolist();

            // search
            connection = new sqlconnection(connectionstring);
            connection.open();

            // each database
            list<string> databases = new list<string>();
            string databaseslookup = "select name from master.dbo.sysdatabases";
            sqldatareader reader = new sqlcommand(databaseslookup, connection).executereader();
            while (reader.read())
            {
                // capture
                databases.add(reader.getvalue(0).tostring());
            }

            // build quintessential folder
            string logsdirectory = @"e:\logs";
            if (!directory.exists(logsdirectory))
            {
                // build
                directory.createdirectory(logsdirectory);
            }
            string basefolder = @"e:\logs\sqlmetaproberesults";
            if (!directory.exists(basefolder))
            {
                // build
                directory.createdirectory(basefolder);
            }

            // close reader
            reader.close();                

            // sort databases
            databases.sort();

            // new space
            console.writeline(environment.newline + " found " + databases.count + " database(s) to scan" + environment.newline);

            // deep scan
            foreach (string databasename in databases)
            {
                // skip skip databases
                if (skipdatabases.contains(databasename))
                {
                    // skip 
                    continue;
                }

                // select the database
                new sqlcommand("use " + databasename, connection).executenonquery();

                // table count
                int tableposition = 1;

                try
                {
                    // defaulting
                    list<string> tablenames = new list<string>();

                    // schema examination
                    datatable table = connection.getschema("tables");

                    // query tables
                    string tableslookup = "select table_name from information_schema.tables";
                    using (sqldatareader databasereader = new sqlcommand(tableslookup, connection).executereader())
                    {
                        // get data
                        while (databasereader.read())
                        {
                            // push
                            if (databasereader.getvalue(0).tostring().trim() != string.empty)
                            {
                                tablenames.add(databasereader.getvalue(0).tostring());
                            }
                        }

                        // bail
                        databasereader.close();
                    }

                    // sort
                    tablenames.sort();                        

                    // cycle tables
                    foreach (string tablename in tablenames)
                    {
                        // build data housing
                        string databasepathname = @"e:\logs\\sqlmetaproberesults" + databasename;
                        string tabledirectorypath = @"e:\logs\sqlmetaproberesults\" + databasename + @"\" + tablename;

                        // count first
                        int totalentitycount = 0;
                        int currententityposition = 0;                            
                        string countquery = "select count(*) from " + databasename + ".dbo." + tablename;
                        using (sqldatareader entitycountreader = new sqlcommand(countquery, connection).executereader())
                        {
                            // query count
                            while (entitycountreader.read())
                            {
                                // capture
                                totalentitycount = int.parse(entitycountreader.getvalue(0).tostring());
                            }

                            // close
                            entitycountreader.close();
                        }

                        // write the objects into the houseing
                        string jsonlookupquery = "select * from " + databasename + ".dbo." + tablename;
                        using (sqldatareader tablereader = new sqlcommand(jsonlookupquery, connection).executereader())
                        {                                                
                            // defaulting
                            list<string> fieldvaluelisting = new list<string>();

                            // read continue
                            while (tablereader.read())
                            {                                   
                                // increment
                                currententityposition++;

                                // defaulting
                                string identity = null;

                                // gather data
                                for (int i = 0; i < tablereader.fieldcount; i++)
                                {
                                    // set
                                    if (tablereader.getname(i).toupper() == "id")
                                    {
                                        identity = tablereader.getvalue(0).tostring();
                                    }
                                    else
                                    {
                                        // build column data entry
                                        string thiscolumn = tablereader.getvalue(i) != null ? "'" + tablereader.getvalue(i).tostring().trim() + "'" : string.empty;

                                        // piece
                                        fieldvaluelisting.add(thiscolumn);
                                    }
                                }

                                // path-centric
                                string explicitidentity = identity ?? guid.newguid().tostring().replace("-", string.empty).tolower();
                                string filepath = tabledirectorypath + @"\" + "obj." + explicitidentity + ".json";
                                string restringed = jsonconvert.serializeobject(fieldvaluelisting, newtonsoft.json.formatting.indented);
                                string percentagemark = ((double)tableposition / (double)tablenames.count * 100).tostring("#00.0") + "%";                                                      
                                string thismarker = guid.newguid().tostring().replace("-", string.empty).tolower();
                                string entitypercentmark = string.empty;
                                if (totalentitycount != 0 && currententityposition != 0)
                                {
                                    // percent mark
                                    entitypercentmark = ((double)currententityposition / (double)totalentitycount * 100).tostring("#00.0") + "%";
                                }

                                // search term verify
                                if (searchterm.trim() != string.empty)
                                {
                                    // search term scenario
                                    if (restringed.tolower().trim().contains(searchterm.tolower().trim()))
                                    {
                                        // lazy build
                                        if (!directory.exists(tabledirectorypath))
                                        {
                                            // build
                                            directory.createdirectory(tabledirectorypath);
                                        }

                                        // has the term
                                        string idmolding = identity == null || identity == string.empty ? "no identity" : identity;
                                        file.writealltext(filepath, restringed);
                                        colorconsole.print(percentagemark + " => " + databasename + "." + tablename + "." + idmolding + "." + thismarker + " (" + entitypercentmark + ")", consolecolor.green, consolecolor.black, true);
                                    }
                                    else
                                    {
                                        // show progress                                            
                                        string idmolding = identity == null || identity == string.empty ? "no identity" : identity;
                                        colorconsole.print(percentagemark + " => " + databasename + "." + tablename + "." + idmolding + "." + thismarker + " (" + entitypercentmark + ")", consolecolor.yellow, consolecolor.black, true);
                                    }
                                }
                            }

                            // close
                            tablereader.close();
                        }

                        // increment
                        tableposition++;
                    }                        
                }
                catch (exception err)
                {
                    colorconsole.print("db.tables!: " + err.message, consolecolor.red, consolecolor.white, false);                        
                }
            }
        }
        catch (exception err)
        {
            colorconsole.print("kaboom!: " + err.tostring(), consolecolor.red, consolecolor.white, false);                
        }
        finally
        {
            try { connection.close(); }
            catch { }
        }


        // await
        colorconsole.print("done.");
        console.readline();
    }
    #endregion

    #region cores
    public static string generatehash(string inputstring)
    {
        // defaulting
        string calculatedchecksum = null;

        // calculate
        sha256managed checksumbuilder = new sha256managed();
        string hashstring = string.empty;
        byte[] hashbytes = checksumbuilder.computehash(encoding.ascii.getbytes(inputstring));
        foreach (byte thebyte in hashbytes)
        {
            hashstring += thebyte.tostring("x2");
        }
        calculatedchecksum = hashstring;

        // return
        return calculatedchecksum;
    }
    #endregion


    #region colors
    public class colorconsole
    {
        #region defaulting
        public static consolecolor defaultbackground = consolecolor.darkblue;
        public static consolecolor defaultforeground = consolecolor.yellow;
        public static string defaultbackporch = "                                                                              ";
        #endregion

        #region printer cores
        public static void print(string phrase)
        {
            // use primary
            print(phrase, defaultforeground, defaultbackground, false);
        }
        public static void print(string phrase, consolecolor customforecolor)
        {
            // use primary
            print(phrase, customforecolor, defaultbackground, false);
        }
        public static void print(string phrase, consolecolor custombackcolor, bool inplace)
        {
            // use primary
            print(phrase, defaultforeground, custombackcolor, inplace);
        }
        public static void print(string phrase, consolecolor customforecolor, consolecolor custombackcolor)
        {
            // use primary
            print(phrase, customforecolor, custombackcolor, false);
        }
        public static void print(string phrase, consolecolor customforecolor, consolecolor custombackcolor, bool inplace)
        {
            // capture settings
            consolecolor captureforeground = console.foregroundcolor;
            consolecolor capturebackground = console.backgroundcolor;

            // change colors
            console.foregroundcolor = customforecolor;
            console.backgroundcolor = custombackcolor;

            // write
            if (inplace)
            {
                // from beginning of this line + padding
                console.write("\r" + phrase + defaultbackporch);
            }
            else
            {
                // normal write
                console.write(phrase);
            }

            // revert
            console.foregroundcolor = captureforeground;
            console.backgroundcolor = capturebackground;
        }
        #endregion
    }
    #endregion
}
}

score:2

this can be done but will not be pretty. there are several possible solutions.

1. write the queries for every table yourself and execute them all in your query method.

var users = context.users
    .where(x => x.firstname.contains(txt) || x.lastname.contains(txt))
    .tolist();

var products = context.products
    .where(x => x.productname.contains(txt));

var result = user.cast<object>().concat(products.cast<object>());

2. fetch all (relevant) tables into memory and perform the search using reflection. less code to write payed with a huge performance impact.

3. build the expression trees for the searches using reflection. this is probably the best solution but it is probably challenging to realize.

4. use something designed for full-text search - for example full-text search integrated into sql server or apache lucene.

all linq solution will (probably) require one query per table which imposes a non-negligible performance impact if you have many tables. here one should look for a solution to batch this queries into a single one. one of our projects using linq to sql used a library for batching queries but i don't know what it name was and what exactly it could do because i worked most of the time in the front-end team.

score:3

it's probably 'possible', but most databases are accessed through web or network, so its a very expensive operation. so it sounds like bad design.

also there is the problem of table and column names, this is probably your biggest problem. it's possible to get the column names through reflection, but i don't know for table names:

foreach (propertyinfo property in typeof(tentity).getproperties())
   yield return property.name;

edit: @ben, you'r right my mistake.

score:7

linq to sql, orms in general, even sql is a bad match for such a query. you are describing a full-text search so you should use sql server's full text search functionality. full text search is available in all versions and editions since 2000, including sql server express. you need to create an fts catalog and write queries that use the contains, freetext functions in your queries.

why do you need such functionality? unless you specifically want to fts-enable your application, this is a ... strange ... way to access your data.

score:8

ask your boss the following:

"boss, when you go to the library to find a book about widgets, do you walk up to the first shelf and start reading every book to see if it is relevant, or do you use some sort of pre-compiled index that the librarian has helpfully configured for you, ahead of time?"

if he says "well, i would use the index" then you need a full text index.

if he says "well, i would start reading every book, one by one" then you need a new job, a new boss, or both :-)


Related Query

More Query from same tag