t-sql学习中--创建表结构、修改表结构

要使用带有空格的表名,需要用方括号或者双引号把表名括起来。而且得确保用SET QUOTED_IDENTIFIER被设置为ON。默认情况下SET QUOTED_IDENTIFIER已经被设置为ON了。但是如果它被设置为OFF,使用括号或者双引号把带空格的表名括起来是有风险的。

创建表可以使用页压缩或者行压缩。页压缩本身已经包含了行压缩。
修改表可以做这些事:添加或者删掉列,包括计算列。新列被放在表的列的最后。修改列的数据类型,修改列的可空性(从可空变成不可空,或者反过来)。添加或者删除一个约束,包括下面这些约束:主键约束(Primary key constraint)、唯一性约束(Unique constraint)、外键约束(Foreign key constraint)、检查约束(Check constraint)、默认约束(Default constraint)
修改表不可以做这些事:修改列名,添加一个特征ID属性(Identity)、删掉一个特征ID属性。

创建和修改表实践:
在这个实践中,你将使用ALTER TABLE命令来添加一个列行一个列,并修改数据类型。本书的附送文件中有用于本章本课项目的文件。如果你在完成练习时遇到了一个问题,你可以从解决方案文件夹中重新安装项目文件再重试一次。
In this practice, you use the ALTER TABLE command to add columns to a table and change data types.
If you encounter a problem completeing a exericise, you can install then completed projects from the Solution folder that is provided with the compainion content for this chapter and lesson.

Exercise 1 Use ALTER TABLE to ADD and Modify Columns
练习一:使用ALTER TABLE来添加和修改列

Examine the following CREATE TABLE statement, from the TSQL2012.sql script, that is used to create the Production.Categories table.

从TSQL2012.sql脚本开始,测试下面的CREATE TABLE语句,它是用来创建一个Production.Categories表。

SQL/*From TSQL2012.sql:
-- Create table Production.Categories
CREATE TABLE Production.Categories
(
categoryid INT NOT NULL IDENTITY,
categoryname NVARCHAR(15) NOT NULL,
description NVARCHAR(200) NOT NULL,
CONSTRAINT PK_Categories PRIMARY KEY(categorid)
);
*/

In this exercise, you create a similar table by the name of Production.CategoriesTest, One column at a time. Then you use the SET IDENTITY_INSERT command to insert a new row.
在这个练习中,你创建了一个简单表,名为Production.CategoriesTest,最初它只有一列。然后你使用SET IDENTITYINSERT命令来插入一个新行。

  1. Start a new query windows in SSMS, and make sure a fresh copy of the TSQL2012 database is on the server. In this exercise, you create a extra table and then drop it in the TSQL2012 database.

    在SQL Server企业管理器中新建一个查询,并确保服务器里有一个原封不动的TSQL2012数据库的副本。在这个练习中,你创建了一个额外的表,并把它放入TSQL2012数据库。

  2. CREATE the table with one column. Execute the following statements in order to create your copy of the original table, but just one column to start with.
    创建一个只有一列的表。执行下面的语句以创建你的源表的副本,但是最初只有一列。

    SQLUSE TSQL2012;
    GO
    CREATE TABLE Production.CategoriesTest
    (
        categoryid INT NOT NULL IDENTITY
    );
    GO
    
  3. Add the categoryname and description columns to match the original table.
    添加categoryname列和description列以匹配源表。

    SQLALTER TABLE Production.CategoriesTest
        ADD categoryname NVARCHAR(15) NOT NULL;
    GO
    ALTER TABLE Production.CategoriesTest
        ADD description NVARCHAR(200) NOT NULL;
    GO
    
  4. Now you attempt an insert into the copy table from the original table, but the Insert will fail. Execute the following.
    现在,你尝试从源表中插入数据副本。但是这个插入将失败。执行下面的语句:

    SQLINSERT Production.CategoriesTest (categoryid, categoryname, description)
        SELECT categoryid, categoryname, description
        FROM Production.Categories;
    GO
    
  5. Try again with IDENTITY_INSERT ON, which allows a row to be inserted with an explicit identity value.
    把IDENTITY_INSERT设置为ON后再重试一下。这个语句让你可以插入带有明确的特征ID属性值的行。

    SQLSET IDENTITY_INSERT Production.CategoriesTest ON;
    INSERT Production.CategoriesTest (categoryid, categoryname, description)
        SELECT categoryid, categoryname, description
        FROM Production.Categories;
    GO
    SET IDENTITY_INSERT Production.CategoriesTest OFF;
    
  6. To clean up, drop the table. You can skip this step if you are going to the next exercise.
    为了清理,删掉这个表。你可以跳过这一步,如果你将继续下一个练习。

    SQLIF OBJECT_ID('Production.categoriesTest','U') IS NOT NULL
        DROP TABLE Production.CategoriesTest;
    GO
    

Eexrcise 2 Work with NULL Columns in Tables
练习二:操作表的空行

In this exercise you use the table from the previous exercise and explore the consequences of adding a column that does not and then does allow NULL.

在这个练习中,你使用上一个练习创建的表。察看添加一个允许空以及不允许空的列的结果。

  1. Create and populate the table from the previous exercise by executing the following code. You can skip this step if you still have the table in TSQL2012 from the previous exercise.
    执行下面的语句,从上一个练习中创建和移值表,如果你在上一个练习中在TSQL2012中创建的表还保留着,你可以跳过这一步。

    SQL-- Create table Production.CategoriesTest
    CREATE TABLE Production.CategoriesTest
    (
        categoryid INT NOT NULL IDENTITY,
        categoryname NVARCHAR(15) NOT NULL,
        description NVARCHAR(200) NOT NULL,
        CONSTRAINT PK_Categories PRIMARY KEY(categoryid)
    );
    -- Populate the table Production.CategoriesTest
    SET IDENTITY_INSERT Production.CategoriesTest ON;
    INSERT Production.CategoriesTest (categoryid, categoryname, description)
        SELECT categoryid, categoryname, description
        FROM Production.Categories;
    GO
    SET IDENTITY_INSERT Production.CategoriesTest OFF;
    GO
    
  2. Make the description column larger.
    增加description列的数据容量。

    SQLALTER TABLE Production.CategoriesTest
        ALTER COLUMN description NVARCHAR(500);
    GO
    
  3. Test for the existence of any NULLs in the description column. Note there are none:
    测试是否存在任何description列为空的行。注意到没有这样的行:

    SQLSELECT description
        FROM Production.CategoriesTest
        WHERE categoryid = 8; -- Seaweed and fish
    
  4. Try to change a value in the description column to NULL. This fails.
    尝试把这一行的description列设置为空值。结果失败了。

    SQLUPDATE Production.CategoriesTest
        SET description = NULL
        WHERE categoryid = 8;
    GO
    
  5. Alter the table and make the description column allow NULL.
    修改表,使description允许为空。

    SQLALTER TABLE Production.CategoryesTest
        ALTER COLUMN description NVARCHAR(500) NULL;
    GO
    
  6. Now retry the update. This works.
    现在重试更新。这次起作用了。

    SQLUPDATE Production.CategoriesTest
        SET description = NULL
        WHERE categoryid = 8;
    GO
    
  7. Attemp to change the column back to NOT NULL. This fails.
    尝试把这一列改回不允许空,这次失败了。

    SQLALTER TABLE Production.CategoriesTest
        ALTER COLUMN descrption NVARCHAR(500) NOT NULL;
    GO
    
  8. Retry the update, but give the description back its original value.
    重试更新,将description值恢复到它的原始值。

    SQLUPDATE Production.CategoriesTest
        SET description = 'Seaweed and fish'
        WHERE categoryid = 8;
    GO
    
  9. Change the description column back to NOT NULL. This succeeds.
    把description改为不能为空,这次成功了。

    SQLALTER TABLE Production.CategoriesTest
        ALTER COLUMN description NVARCHAR(500) NOT NULL;
    GO
    
  10. To clean up, drop the table.
    为了清理,删除这个表。

    SQLIF OBJECT_ID('Production.CategoriesTest', 'U') IS NOT NULL
        DROP TABLE Production.CategoriesTest;
    GO
    

Lesson Summary
本课小结
* Creating a table involves specifying a table schema as a namespace or container for the table.
创建一个表,包括指定表的架构名,作为命名空间,或者作为表的容器。

  • Name tables and columns carefully and descriptively.
    仔细地、描述性地命名表名以及列名。

  • Choose the most efficient and accurate date types for columns.
    为列选择最有效而且最精确的数据类型。

  • Choose the appropriate remaining properties of columns, such as the identity property and whether a column should allow NULLs.
    为列选择恰当的保留属性,比如说特征ID属性,以及一列是否允许空。

  • You can specify whether a table should be compressed when creating the table.
    你在创建表时,可以指定一个表是否需要压缩。

  • You can use ALTER TABLE to change most properties of columns after a table has been created.
    你在创建表之后,可用ALTER TABLE来修改大多数列的属性。

Lession Review
本课复习

Answer the following questions to test your knowledge of the information in this lesson. You can find the answers to these question and explainations of why each answer choice is correct or incorrect in the “Answers” session at the end of this chapter.
回答下面的问题,以测试你的对本节课所讲的知识的掌握度。你可以在本章末尾的“答案”部分找到这些问题的答案,以及解释为什么这些答案选项是对或者是错的。

  1. Which of the following are T-SQL regular identifiers?(Choose all that allpy.)(A,D) 下面哪些是T-SQL正规的标识符?
    A. categoryname
    B. category name
    C. category$name
    D. category_name

  2. Which data type should be used in place of TIMESTAMP?(B) 哪种数据类型可以用来替代TIMESTAMP?
    A. VARBINARY
    B. ROWVERSION
    C. DATETIME2
    D. TIME

  3. How can you express that the column categoryname allow NULLs?(D)你如何表达categoryname列允许空?
    A. categoryname PERMIT NULL NVARCHAR(15)
    B. categoryname NVARCHAR(15) ALLOW NULL
    C. categoryname NVARCHAR(15) PERMIT NULL
    D. categoryname NVARCHAR(15) NULL

    原文作者:SQL
    原文地址: https://segmentfault.com/a/1190000002777831
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞