سؤال

I've been creating a few power shell scripts and Iv'e mainly been using Invoke-Sqlcmd as a way to query the database or input .sql files, but I have been having some trouble with containing access and killing processes.

Iv'e been using SMO to kill the processes

$SQlSvr1 = New-Object Microsoft.SqlServer.Management.Smo.Server $serverInstance
$SQlSvr1.KillAllprocesses($databaseMain)

and then using Invoke-Sqlcmd to run my processes, it was all running well until I started receiving erorrs such as

A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.) 

and If I didn't kill the process it returns

Exclusive access could not be obtained because the database is in use.

So my question is, what is the best process to regenerate or keep a stable connection I don't mine changing everything to SMO or SQLConnection or if there is a way to make a single connection using Invoke-Sqlcmd, but kill/requeue everytime I use an invoke.

The script in question first Backs-up my databases, runs and updates using patch scripts inside a try/catch ifthere is an error the script will backup inside the catch, all using Invoke-Sqlcmd except for the kill processes.

هل كانت مفيدة؟

المحلول

All three have their uses.

I like invoke-sqlcmd for quick & dirty queries, or queries that already exist in other files (as you can pass in a file parameter). I've never had to deal with the error you had that sparked the question, though.

I use SQLConnection & SQLCommand when I need more safety - parameterized queries, for example - or want to maintain a more persistent connection - when I'm running a lot of queries in rapid succession - so that I don't hammer the server with a lot of connections in a short period of time.

SMO I haven't really used, but I would reserve that for managing at the "system" level - jobs, backups, etc. You can do pretty much anything with SMO - Wayne Sheffield had examples of adding & altering tables & stored procedures in his blog last month (I can't link to the posts, as my office firewall blocks it for unknown reasons). I would normally do that through a T-SQL query, but it works both ways, and I'm sure there must be some advantage do doing it with SMO.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top