创建 Products 表后,即可使用 INSERT 语句将数据插入表中。 插入数据后,将通过使用 UPDATE 语句更改行的内容。 你将使用 UPDATE 语句的 WHERE 子句将更新限制为单个行。 这四个语句将输入以下数据。
ProductID | ProductName | 价格 | 产品描述 |
---|---|---|---|
1 | 钳 | 12.48 | 工作台夹具 |
50 | 螺丝刀 | 3.17 | 平头 |
75 | 轮胎撬棒 | 用于更改轮胎的工具。 | |
3000 | 3mm 支架 | .52 |
基本语法如下:INSERT、表名、列的列表、VALUES,然后是要插入的值的列表。 行前面的两个连字符指示行是注释,编译器将忽略文本。 在这种情况下,注释说明允许的语法变体。
将数据插入表中
执行以下语句,将一行插入到在上一个任务中创建的
Products
表中。 这是基本语法。-- Standard syntax INSERT dbo.Products (ProductID, ProductName, Price, ProductDescription) VALUES (1, 'Clamp', 12.48, 'Workbench clamp') GO
以下语句显示如何通过在字段列表(在圆括号中)中和值列表中均切换
ProductID
和ProductName
的位置,更改提供参数的顺序。-- Changing the order of the columns INSERT dbo.Products (ProductName, ProductID, Price, ProductDescription) VALUES ('Screwdriver', 50, 3.17, 'Flat head') GO
以下语句演示,只要值是按正确顺序列出的,列的名称就是可选的。 此语法很常见,但不建议这样做,因为其他人可能更难理解你的代码。
NULL
为Price
列指定,因为此产品的价格尚未知。-- Skipping the column list, but keeping the values in order INSERT dbo.Products VALUES (75, 'Tire Bar', NULL, 'Tool for changing tires.') GO
只要在默认架构中访问和更改表,架构名称就是可选的。 由于
ProductDescription
列允许 Null 值,而且没有提供值,因此可以从语句中完全删除ProductDescription
列的名称和值。-- Dropping the optional dbo and dropping the ProductDescription column INSERT Products (ProductID, ProductName, Price) VALUES (3000, '3mm Bracket', .52) GO
更新产品表
键入并执行以下
UPDATE
语句,将第二种产品的ProductName
从Screwdriver
更改为Flat Head Screwdriver
。UPDATE dbo.Products SET ProductName = 'Flat Head Screwdriver' WHERE ProductID = 50 GO