Monday, February 7, 2011

Writing Transact-SQL (Part 4)

Read the data in a Table

We use SELECT statement  to read the data in a table. The SELECT statement is one of the most important T-SQL statement.
  • Type and execute the following statements to read the data in the Products table.
          SELECT ProductID, ProductName, Price, ProductDescription
          FROM dbo.Products
           GO
  • You can use an asterisk to select all the columns in the table. This is often used in ad hoc queries. You should provide the column list in you permanent code so that the statement will return the predicted columns, even if a new column is added to the table later.
         SELECT * FROM Products
         GO
  • You can omit columns that you do not want to return. The columns will be returned in the order that they are listed.
         SELECT ProductName, Price
         FROM dbo.Products
         GO
  • Use a WHERE clause to limit the rows that are returned to the user.
           SELECT ProductID, ProductName, Price, ProductDescription
           FROM dbo.Products
           WHERE ProductID < 60
           GO
  • You can work with the values in the columns as they are returned. The following example performs a mathematical operation on the Price column. Columns that have been changed in this way will not have a name unless you provide one by using the AS keyword.
          SELECT ProductName, Price * 1.07 AS CustomerPays
          FROM dbo.Products
          GO

No comments:

Post a Comment