微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

怎么使用SQL语句将行和列进行转换

小编给大家分享一下怎么使用sql语句将行和列进行转换,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

  如何使用sql语句将行和列进行转换

  if exists ( select * from sysdatabases where [name]='TestDB')

  print 'Yes, the DB exists'

  else

  print 'No, need a new one?'

  --新建一个数据库

  create database TestDB on

  (

  name = 'TestData',

  filename = 'G:DBSKeyTest.mdf',

  size = 3,

  filegrowth = 2

  )

  log on

  (

  name = 'TestLog',

  filename = 'G:DBSKeyTest.ldf',

  size = 3,

  filegrowth = 10

  )

  --drop database TestDB

  use TestDB

  go

  --新建一个

  create table [scores]

  (

  [ID] int identity(1,1) primary key,

  [Student] varchar(20) ,

  [Subject] varchar(30),

  [score] float

  )

  --drop table [scores]

  如何使用sql语句将行和列进行转换

  --修改表中的一列

  alter table scores alter column [Student] varchar(20) not null

  --新增一列

  alter table scores add Birthday datetime

  --删除一列

  alter table scores drop column Birthday

  --往表中插入单条数据,方法1:带列名

  insert into scores(Student,Subject,score)

  values('张三','语文','90')

  --往表中插入单条数据,方法2:不带列名,但要求值的类型要和列字段类型对应

  insert into scores

  values('张三','英语','95')

  --插入多条数据:用union或者union all

  insert into scores(Student,Subject,score)

  select '李四','语文','89'

  union all

  select '李四','英语','78'

  --删除表中数据,没有条件时,删除所有

  delete from scores where ID in(7,8)

  --修改表中数据

  update scores

  set Student='王五',score='94'

  where ID=10

  --查看数据

  select * from scores

  --查看表中最大的identity值

  select @@identity

  --或者利用dbcc命令查看表中最大的identity值

  dbcc checkident('scores',noreseed)

  --创建视图,全部省略视图的属性列名,由子查询目标列的字段组成

  create view StudentView

  as

  select Student,Subject,score

  from scores

  --加上with check option,以后对视图的操作(增,改,删,查)都会自动加上where ID>3

  /*

  create view StudentView

  as

  select Student,Subject,score

  from scores

  where ID>3

  with check option

  */

  --创建视图,全部定义属性列名,需要定义列名的情况:

  ----某个目标列(子查询)不是单纯的属性列,而是聚集函数或列表达式

  ----多表连接时选出了几个同名列

  ----需要在视图中为某个列启用新的更合适的名字

  create view IS_Student(Student,Subject,Maxscore)

  as

  select Student,Subject,score

  from scores

  where score=(select max(score) from scores)

  --查询视图,和基本表完全样,只不过如果视图中有with check option,会自动加上那个条件

  select *

  from StudentView

  --查询自定义列名的视图

  select *

  from IS_Student

  --对视图的insert/delete/update,和对基本表的操作一样,并且最终都是用RDBMS自动转换为对基本表的更新

  --并不是所有的视图都是可更新的,因为有些视图的更新不能有意义的转换成对相应基本表的更新

  --删除视图

  drop view StudentView

  --查询数据库是否存在

以上是“怎么使用sql语句将行和列进行转换”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程之家行业资讯频道!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐