简体   繁体   English

t-SQL USE关键字问题

[英]t-SQL USE keyword issue

Say, I just created a database, then created a login and and now I need to assign a user to it. 假设我刚刚创建了一个数据库,然后创建了一个登录名,现在我需要为其分配用户。 So I do: 所以我做:

CREATE DATABASE [testdb2] COLLATE SQL_Latin1_General_CP1_CI_AS;
CREATE LOGIN testusr1 WITH PASSWORD = 'mystrongpassword';
USE [testdb2];
CREATE USER testusr1 FOR LOGIN testusr1;

But the USE line returns this error: 但是USE行返回此错误:

Database 'testdb2' does not exist. 数据库“ testdb2”不存在。 Make sure that the name is entered correctly. 确保正确输入名称。

Add some GO commands: 添加一些GO命令:

Signals the end of a batch of Transact-SQL statements to the SQL Server utilities. 向SQL Server实用程序发出一批Transact-SQL语句的结束信号。

Eg, 例如,

CREATE DATABASE [testdb2] COLLATE SQL_Latin1_General_CP1_CI_AS;
GO
CREATE LOGIN testusr1 WITH PASSWORD = 'mystrongpassword';
GO
USE [testdb2];
GO
CREATE USER testusr1 FOR LOGIN testusr1;

GO is not a Transact-SQL statement; GO不是Transact-SQL语句; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor. 它是sqlcmd和osql实用程序以及SQL Server Management Studio代码编辑器可以识别的命令。 SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server. SQL Server实用程序将GO解释为一种信号,表示它们应将当前一批Transact-SQL语句发送到SQL Server实例。 The current batch of statements is composed of all statements entered since the last GO, or since the start of the ad hoc session or script if this is the first GO. 当前的语句批处理由上一个GO或自临时会话或脚本(如果这是第一个GO)开始以来输入的所有语句组成。 A Transact-SQL statement cannot occupy the same line as a GO command. Transact-SQL语句不能与GO命令占据同一行。 However, the line can contain comments. 但是,该行可以包含注释。 Users must follow the rules for batches. 用户必须遵循批处理规则。 For example, any execution of a stored procedure after the first statement in a batch must include the EXECUTE keyword. 例如,批处理中的第一条语句之后对存储过程的任何执行都必须包含EXECUTE关键字。 The scope of local (user-defined) variables is limited to a batch, and cannot be referenced after a GO command. 局部(用户定义)变量的范围仅限于批处理,并且在GO命令后不能引用。

You have to use GO after your CREATE DATABASE statement, and also after your CREATE LOGIN statement. 您必须在CREATE DATABASE语句之后以及CREATE LOGIN语句之后使用GO。
GO is used as a batch separator. GO用作批处理分隔符。 You can changed this if you want to use something else as a batch separator instead of GO. 如果您要使用其他代替而不是GO的批处理分隔符,则可以更改此设置。 Go to Tools -> Options -> Query Execution, and see the Batch Separator section. 转到工具->选项->查询执行,然后查看批处理分隔符部分。
GO can also be used with an int parameter for example: GO也可以与int参数一起使用,例如:

INSERT INTO #tmp
SELECT 1, 2, 3
GO 10

Which will insert the values into #tmp 10 times. 这会将值插入#tmp 10次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM