使用 SELECT 语句可以读取表中的数据。 SELECT 语句是最重要的 Transact-SQL 语句之一,其语法有许多变体。 在本教程中,你将使用五个简单版本。
读取表中的数据
键入并执行以下语句以读取
Products
表中的数据。-- The basic syntax for reading data from a single table SELECT ProductID, ProductName, Price, ProductDescription FROM dbo.Products GO
可以使用星号选择表中的所有列。 这通常用于临时查询。 你应该在永久代码中提供列列表,以便该语句将返回预测列,即使以后将新列添加到表中也是如此。
-- Returns all columns in the table -- Does not use the optional schema, dbo SELECT * FROM Products GO
可以省略不想返回的列。 列将按列出的顺序返回。
-- Returns only two of the columns from the table SELECT ProductName, Price FROM dbo.Products GO
使用
WHERE
子句可以限制返回给用户的行。-- Returns only two of the records in the table SELECT ProductID, ProductName, Price, ProductDescription FROM dbo.Products WHERE ProductID < 60 GO
您可以在返回列中的值时使用它们。 以下示例对
Price
列执行数学运算。 除非使用AS
关键字提供名称,否则以这种方式更改的列将不具有名称。-- Returns ProductName and the Price including a 7% tax -- Provides the name CustomerPays for the calculated column SELECT ProductName, Price * 1.07 AS CustomerPays FROM dbo.Products GO
SELECT 语句中有用的函数
有关可用于在 SELECT 语句中使用数据的某些函数的信息,请参阅以下主题:
字符串函数 (Transact-SQL) | 日期和时间数据类型及函数 (Transact-SQL) |
数学函数 (Transact-SQL) | 文本与图像函数 (Transact-SQL) |