Jump to content

SQL - How To Check Multiple Databases For Column?


Go to solution Solved by mrider,

Recommended Posts

Hi all,

So, I have a script that will scan through all my SQL databases that are running and check to see if their name matches the name I'm looking for and, if it finds a match, it will check a column's value and return it.

The script works fine, but it's so incredibly slow since there are only 2 out of 26 in my list that are matched. Is there a faster way to go about this?

I've attached the _SQL.au3 file I'm using, for easier testing  ^_^

Thanks for the help!

#include <_SQL.au3>
#include <Array.au3>

Dim $sNRM_SQLUser = "username"
Dim $sNRM_SQLPass = "password"
Dim $sNRM_SQLHost = "(local)"
Dim $bNRM_SQLAuth = True
Global $sNRM_DatabaseName = "NRM"

Dim $iDatabases = NRM_ScanDatabases($sNRM_SQLUser, $sNRM_SQLPass, $sNRM_SQLHost, $bNRM_SQLAuth)
MsgBox(0, "", "Count: " & $iDatabases)

Func NRM_ScanDatabases($sUser, $sPass, $sHost, $bSQLAuth)
    ; If the SQL connection succeeded, then get the DB count
    Local $iCount = 0
    Local $aDatabaseList = _SQL_GetDatabaseArray($sHost, $sUser, $sPass, $bSQLAuth)

    If IsArray($aDatabaseList) Then
        For $i = 1 To UBound($aDatabaseList) - 1
            SplashTextOn("", "Querying database " & $i & " of " & (UBound($aDatabaseList) - 1), 300, 45, Default, Default, $DLG_NOTITLE)
            ConsoleWrite("--> Checking: " & $aDatabaseList[$i][0]  & @CRLF)
            If StringInStr($aDatabaseList[$i][0], $sNRM_DatabaseName) > 0 Then
                Local $iNRM_DBVersion = _SQL_GetNRMVersion($sHost, $sUser, $sPass, $bSQLAuth, $aDatabaseList[$i][0])
                If $iNRM_DBVersion <> -1 Then
$iCount += 1
ConsoleWrite($aDatabaseList[$i][0] & @CRLF)
EndIf
            EndIf
            SplashOff()
        Next
    EndIf
    Return $iCount
EndFunc

Func _SQL_GetDatabaseArray($sServer, $sUser, $sPass, $bSQLAuth = True)
    Local $oADODB
    Local $aDatabases
    Local $iRows, $iColumns
    
    ; Register the error handler to prevent a hard crash on COM errors
    _SQL_RegisterErrorHandler()
    
    $oADODB = _SQL_Startup()
    If $oADODB = $SQL_ERROR Then
        Msgbox(16, "Error", _SQL_GetErrMsg())
        Return -1
    EndIf
    
    _SQL_ConnectionTimeout(-1, 5)
    If $bSQLAuth Then
        $oADODB.ConnectionString = 'Provider=SQLOLEDB.1;Password=' & $sPass & ';Persist Security Info=False;User ID=' & $sUser & ';Initial Catalog="";Data Source=' & $sServer
    Else
        $oADODB.ConnectionString = 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog="";Data Source=' & $sServer
    EndIf
    $oADODB.Open
    
    If _SQL_GetTable2D(-1, "select [name] from master.dbo.sysdatabases where dbid > 4;", $aDatabases, $iRows, $iColumns) = $SQL_ERROR Then
        Msgbox(16, "Error", _SQL_GetErrMsg())
    EndIf
    _SQL_Close()

    Return $aDatabases
EndFunc

Func _SQL_GetNRMVersion($sServer, $sUser, $sPass, $bSQLAuth = True, $sDatabase = $sNRM_DatabaseName)
    Local $oADODB
    Local $iDBVersion = -1
    Local $hQuery, $aRow, $sString
    Local $iRows, $iColumns
    Local $sColumnThatHasTheVersion = "AVersion"
    
    ; Register the error handler to prevent a hard crash on COM errors
    _SQL_RegisterErrorHandler()
    
    $oADODB = _SQL_Startup()
    If $oADODB = $SQL_ERROR Then
        Msgbox(16, "Error", _SQL_GetErrMsg())
        Return $iDBVersion
    EndIf
    
    _SQL_ConnectionTimeout(-1, 3)
    If $bSQLAuth Then
        $oADODB.ConnectionString = "Provider=SQLOLEDB.1;Password=" & $sPass & ";Persist Security Info=False;User ID=" & $sUser & ";Initial Catalog=" & $sDatabase & ";Data Source=" & $sServer
    Else
        $oADODB.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" & $sDatabase & ";Data Source=" & $sServer
    EndIf
    $oADODB.Open
    
    If _SQL_GetTable2d(-1, "select " & $sColumnThatHasTheVersion & " from dbo.ADM_SystemVersion;", $aRow, $iRows, $iColumns) = $SQL_OK Then
        If IsArray($aRow) Then $iDBVersion = $aRow[UBound($aRow) - 1][0]
    EndIf
    
    _SQL_Close()
    _SQL_UnRegisterErrorHandler()

    Return $iDBVersion
EndFunc

_sql.au3

Edited by buymeapc
Link to comment
Share on other sites

Did you try other provider ? NCLI ?

What a SQL Version ?

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Just a remark. It's a rather uncommon need to have to scan multiple databases for their names: you're supposed to know your DB(s) filenames. If the schema of these pultiple DBs is same or even close enough, you could consider merging them all in one DB.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

I understand, but the reason I am scanning through all the databases is that this script will be run on different servers, all of which will have a different database layout, so I have no way of know what they have loaded - I just need to see if they have a specific database (or databases) so I can read and display information about it/them.

Link to comment
Share on other sites

I know of a commercial product (for management companies - for accounting offices), which allows the user to create separate databases for each client. Thus, the application checks all databases and displays a list of possible databases to connect.

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • Solution

I did try changing the provider to SQLNCLI10, but it was still about the same speed. I'd like this to work with SQL 2003 and up.

Am I perhaps taking extra steps in my logic that I don't need to take?

 

Generally speaking, making a connection to a database is extremely expensive.  Consequently most data aware applications use a connection pool of previously spun up connections when speed matters.

You are creating numerous connections, and most likely this is your speed issue.

I would suggest altering your logic such that you open the connection to the server once and get the database names with that, and then iterate through each name and switch to that database without closing the connection.  This won't work, but something along the lines of:

_SQL_GetTable2D(-1, "select [name] from master.dbo.sysdatabases where dbid > 4;", $aDatabases, $iRows, $iColumns)
For $i = 1 to Ubound($aDatabases) - 1
    _SQL_Execute(-1, "use [" & $aDatabases[$i][0] & "]")
    _SQL_GetTable2d(-1, "select " & $sColumnThatHasTheVersion & " from dbo.ADM_SystemVersion;", $aRow, $iRows, $iColumns)
    ...
Next

How's my riding? Dial 1-800-Wait-There

Trying to use a computer with McAfee installed is like trying to read a book at a rock concert.

Link to comment
Share on other sites

@mrider: Thank you for your suggestion. You were absolutely correct - I was establishing a connection and closing it each time I connected to a database which was where the immense delay was. I changed it around so it was all in one function utilizing "use [DB]" each time. My check went from 10 seconds down to 2!!

Thank you!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...