简体   繁体   中英

T-SQL equivalent of GO

I'm trying to write a T-SQL script to create a database and the corresponding tables. I'm having a problem where the USE statement complains that the database that I just "created" doesn't exist. If I run the script within SQL Server Management Studio so that I can make use of the GO statement, I don't get this issue.

Is there a T-SQL equivalent of GO that I can use to make sure the CREATE DATABASE gets executed before the USE ?

I've tried BEGIN / COMMIT TRANSACTION and BEGIN / END but they didn't help.

Is there a T-SQL equivalent of GO that I can use to make sure the CREATE DATABASE gets executed before the USE?

Yes. Dynamic SQL. Each dynamic SQL invocation is a parsed, compiled, and executed as a separate batch.

EG:

exec ('
create database foo
 ')
exec ('
use foo
create table bar(id int)
')

Note that when used in dynamic SQL use database only change the database context for the dynamic batch. When control returns to the calling batch, the database context is restored.

In C# you should use separate calls to SqlComand for each batch.
High level steps.

  1. Open connection to master.
  2. Create new database (just create database statement).
  3. Instead of USE call SqlConnection.ChangeDatabase(String) Method
  4. Execute remaining 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