Executing a script via Powershell possibility

netezzapowershellstored-procedures

Let's say I don't happen to have the ability to create a Stored Procedure, but I have to run the same query on a regular basis. Would I be able to put my query in a .txt document and be able to run it from Powershell by calling it? What syntax would I use for myquery.txt to run? Put another way, what's a way to end-run not being able to use a stored procedure on a query that should be made into one?

Best Answer

It depends on your Powershell versions but you have a few options. I tend to use several of them based on the scenario but in your case, why not just call a SQLCMD.EXE from your powershell Script? It has the most compatibility, it's less buggy and more compatible than Invoke-SQLCMD, and outside of DSC I haven't seen MS use osql. It would look something like this:

#Check SQLCMD /? for help and syntax
$Query = "SELECT @@SERVERNAME"
SQLCMD -S "ServerName" -E #integrated security# -q $Query

Otherwise you'd have to install the SQL Server feature pack from v12 and above, then use Invoke-SQLCMD which has some compatibility issues and doesn't provide too many benefits except in certain cases I've found. You also get full SMO functionality with the Feature Pack but it's overkill and has too much config overhead for a simple query.