T-SQL语句基础

一.       查询
二.       插入( insert
语法
insert  [INTO]  < 表名 >  [ 列名 ]  values  < 值列表 >
其中:
Ø      [INTO] 是可选的,可以省略。
Ø      表名是必须的,表的列名是可选的,如果省略, < 值列表 > 中顺序与数据表中字段顺序保持一致。
Ø      多个列名和多个值列表用逗号分隔。
向已存在表中插入一行数据
例: insert into  text (accounttime,phonenumber,charge,calltype,ispaid)
values ( '2008-01-01 00:21:00' , '13252653253' , '1' , '1' , '1' )  
一次插入多行数据
1.    通过 insert  select 语句将现有表中的数据添加到已存在表中
例: insert into text1(accounttime,phonenumber,charge)
select accounttime,phonenumber,charge
from   dbo.accountbill
where charge>22
²      查询得到的数据个数、顺序、数据类型等必须与插入的项保持一致
²      text1 表必须预先创建好,并且与要插入的有相同的字段
²      ID IDENTITY 列,系统会自动生成数据,不需要插入数据,但是已存在的表中必须有 ID 字段
2. 通过 select into 语句将现有表中的数据添加到新表中
(这个新表是执行语句的时候创建的,不能预先存在)
例: select accounttime,phonenumber,charge
into text2
from dbo.accountbill
where charge>22
如果希望新表中的列名称可以自己定义,并且包含 IDENTITY 列,如何插入标识列?因为标识列的数据是不允许指定的,需要按如下语法创建一个新的标识列。
select identity( 数据类型 , 标识种子 , 标识增长量 ) as 列名
into 新表 from 原始表
例: select identity(int,1,1) as ID,accounttime as 时间 , phonenumber as 号码 , charge as 费用
into text4
from dbo.text1
where charge>22
注:必须给标识列指定列名,这里的列名为 ID
3. 通过 union 关键字合并数据进行插入
union 语句用于将两个不同的数据或查询结果组合成一个新的结果集。不同的数据或查询结果要求数据个数、顺序、数据类型都一致,因此,当向表中重复插入多行数据上的时候,可以使用 select …. union 来简化操作。
例: insert text3(accounttime,phonenumber,charge)
select '08  4 2008 12:00AM','13201598688',23 union
select '08  2 2008 12:00AM','13301281806',22.5 union
select accounttime,phonenumber,charge
from dbo.text1
union
select accounttime,phonenumber,charge
from dbo.text2
该语句执行结果向 text3 表中插入了 text1 表的两行和 text2 的所有行数据
三.       更新
四.       删除

本文出自 “刘文斌” 博客,谢绝转载!

你可能感兴趣的:(数据库,基础,职场,语句,休闲)