实验环境

某公司有一台已经安装了SQLServer 2016的服务器,并已经创建了数据库class

需求描述

在数据库PM中创建表products“编号”列的值自动增长并为主键。然后使用T-SQL语句为表格插入如表所示数据。练习查询语句。

初学T-SQL查询语句_数据库

创建名为“ products”表,“编号”列的值自动增长并为主键

create table products

(

编号 int identity (1,1) primary key,

名称 nvarchar(50) not null,

种类 nvarchar(50) not null,

成本 money not null,

出厂日期 datetime not null,

)


插入数据

insert into products (名称,种类,成本,出厂日期)

values ('西瓜','水果','4.100','2017/5/5'),

('芹菜','蔬菜','1.000','2017/4/1'),

('番茄','蔬菜','2.900','2017/5/9'),

('黄瓜','蔬菜','2.200','2017/5/5'),

('香蕉','水果','6.100','2017/5/23'),

('核桃','坚果','28.500','2017/6/2'),

('开心果','坚果','38.110','2017/6/21'),

('蓝莓','水果','50.200','2017/5/15')


其中西瓜的出厂日期输入错误,更改为2017/5/6

update products set 出厂日期='2017/5/6' where 名称='西瓜'

查询成本低于10元的水果信息

select * from products where 成本<10 and 种类='水果'

初学T-SQL查询语句_主键_02

将所有蔬菜的成本上调1元 (初学者不会批量上调,只能逐条改)

update products set 成本='2.00' where 名称='芹菜'

update products set 成本='3.90' where 名称='番茄'

update products set 成本='3.20' where 名称='黄瓜'

查询结果

select * from products

初学T-SQL查询语句_数据_03

查询成本大于3元并小于40元的产品信息,并按照成本从高到低的顺序显示结果

select * from products where 成本>3 and 成本<40 order by 成本 desc (降序)

select * from products where 成本>3 and 成本<40 order by 成本 asc(升序)

初学T-SQL查询语句_数据_04

查询产品成本,价格从高到低显示

select * from products order by 成本 desc

初学T-SQL查询语句_数据_05

查询成本最高的五个产品信息

select top 5 * from products order by 成本 desc

初学T-SQL查询语句_数据_06

查询有哪些产品种类

select distinct 种类 from products

初学T-SQL查询语句_数据_07

将products表中的所有水果的名称、种类和出厂信息并插入新表products_new中。

创建新表products_new

create table products_new

(

名称 nvarchar(50) not null,

种类 nvarchar(50) not null,

出厂日期 datetime not null,

)


查询products表中的所有水果的名称、种类和出厂信息

select 名称,种类,出厂日期 from products where 种类='水果'

初学T-SQL查询语句_主键_08

插入新表products_new中。

insert into products_new (名称,种类,出厂日期)
select 名称,种类,出厂日期 from products where 种类='水果'

结果查询

select * from products_new

初学T-SQL查询语句_数据库_09