简体   繁体   中英

PowerShell Invoke-SqlCmd switching to master database

I have SQL scripts that I run using Invoke-SqlCmd . At the top of each file, I have a USE statement. I noticed that after an error occurs, the user is sent back to their default database (usually master ). The problem is that it continues running the script; it just dumps everything under the master schema. Then I have to go through and remove a bunch of tables, views, etc.

Right now I am just relying on -AbortOnError to quit immediately. However, most of the time, my errors are actually not a big deal. Running the script multiple times would actually resolve the issues, so long as everything ran under the same database. The long-term solution is to fix my SQL scripts, obviously. I was wondering if there was a way to prevent Invoke-SqlCmd from switching to a different database in the meantime.

Example:

# Use Windows Authentication
Invoke-SqlCmd -InputFile "test.sql"

I learned that I did not have a GO immediately following the USE statement. Without it, the USE statement is in the same batch as all the statements following it up to the next GO. The USE wouldn't apply to the other batches.

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