[英]T-SQL equivalent of GO
I'm trying to write a T-SQL script to create a database and the corresponding tables.我正在尝试编写一个 T-SQL 脚本来创建一个数据库和相应的表。 I'm having a problem where the USE
statement complains that the database that I just "created" doesn't exist.我遇到了一个问题, USE
语句抱怨我刚刚“创建”的数据库不存在。 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.如果我在 SQL Server Management Studio 中运行脚本以便可以使用GO
语句,则不会出现此问题。
Is there a T-SQL equivalent of GO that I can use to make sure the CREATE DATABASE
gets executed before the USE
?是否有与 GO 等效的 T-SQL 可用于确保在USE
之前执行CREATE DATABASE
?
I've tried BEGIN
/ COMMIT TRANSACTION
and BEGIN
/ END
but they didn't help.我试过BEGIN
/ COMMIT TRANSACTION
和BEGIN
/ END
但它们没有帮助。
Is there a T-SQL equivalent of GO that I can use to make sure the CREATE DATABASE gets executed before the USE?是否有与 GO 等效的 T-SQL 可用于确保在 USE 之前执行 CREATE DATABASE?
Yes.是的。 Dynamic SQL.动态 SQL。 Each dynamic SQL invocation is a parsed, compiled, and executed as a separate batch.每个动态 SQL 调用都作为单独的批处理进行解析、编译和执行。
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.请注意,在动态 SQL 中use database
仅更改动态批处理的数据库上下文。 When control returns to the calling batch, the database context is restored.当控制返回到调用批处理时,数据库上下文被恢复。
In C# you should use separate calls to SqlComand for each batch.在 C# 中,您应该为每个批处理使用单独的 SqlComand 调用。
High level steps.高级步骤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.