快速入门:使用 Azure Data Studio 连接和查询 SQL Server

本快速入门演示如何使用 Azure Data Studio 连接到 SQL Server,然后使用 Transact-SQL (T-SQL) 语句创建在 Azure Data Studio 教程中使用的 TutorialDB。

先决条件

若要完成本快速入门,需要 Azure Data Studio 以及对 SQL Server 实例的访问权限。

如果没有 SQL Server 的访问权限,请从以下链接选择你的平台(请确保记住 SQL 登录名和密码!):

连接到 SQL Server

  1. 启动 Azure Data Studio。

  2. 首次运行 Azure Data Studio 时,应该会打开“欢迎”页。 如果没有看到“欢迎”页,请选择“帮助”>“欢迎” 。 选择“新建连接”以打开“连接”窗格 :

    Screenshot showing the New Connection icon.

  3. 本文使用 SQL 登录名,但也支持 Windows 身份验证 。 按如下所示填写字段:

    • 服务器名称: 在此处输入服务器名。 例如,localhost。
    • 身份验证类型: SQL 登录名
    • 用户名: SQL Server 的用户名
    • 密码: SQL Server 的密码
    • 数据库名称:<默认>
    • 服务器组:<默认>

    Screenshot showing the New Connection screen.

创建数据库

以下步骤创建一个名为“TutorialDB”的数据库:

  1. 右键单击服务器“localhost”,然后选择“新建查询” 。

  2. 将以下代码片段粘贴到查询窗口,然后选择“运行”。

    USE master;
    GO
    
    IF NOT EXISTS (
          SELECT name
          FROM sys.databases
          WHERE name = N'TutorialDB'
          )
       CREATE DATABASE [TutorialDB];
    GO
    
    IF SERVERPROPERTY('ProductVersion') > '12'
       ALTER DATABASE [TutorialDB] SET QUERY_STORE = ON;
    GO
    

    完成查询后,新的“TutorialDB”会显示在数据库列表中。 如果未显示,请右键单击“数据库”节点,然后选择“刷新” 。

    Screenshot showing how to create database.

创建表

查询编辑器仍连接到 master 数据库,但需要在 TutorialDB 数据库中创建一个表 。

  1. 将连接上下文更改为 TutorialDB:

    Screenshot showing how to change context.

  2. 将查询窗口中的文本替换为以下代码片段,然后选择“ 运行” :

    -- Create a new table called 'Customers' in schema 'dbo'
    -- Drop the table if it already exists
    IF OBJECT_ID('dbo.Customers', 'U') IS NOT NULL
       DROP TABLE dbo.Customers;
    GO
    
    -- Create the table in the specified schema
    CREATE TABLE dbo.Customers (
       CustomerId INT NOT NULL PRIMARY KEY, -- primary key column
       [Name] NVARCHAR(50) NOT NULL,
       [Location] NVARCHAR(50) NOT NULL,
       [Email] NVARCHAR(50) NOT NULL
       );
    GO
    

完成查询后,新的“客户”表会显示在表列表中。 可能需要右键单击“TutorialDB”>“表”节点,然后选择“刷新”。

插入行

将查询窗口中的文本替换为以下代码片段,然后选择“ 运行” :

-- Insert rows into table 'Customers'
INSERT INTO dbo.Customers (
   [CustomerId],
   [Name],
   [Location],
   [Email]
)
VALUES
   (1, N'Orlando', N'Australia', N''),
   (2, N'Keith', N'India', N'keith0@adventure-works.com'),
   (3, N'Donna', N'Germany', N'donna0@adventure-works.com'),
   (4, N'Janet', N'United States', N'janet1@adventure-works.com')
GO

查看查询返回的数据

将查询窗口中的文本替换为以下代码片段,然后选择“ 运行” :

-- Select rows from table 'Customers'
SELECT * FROM dbo.Customers;

Screenshot showing the results from the SELECT query.