插入数据

使用Insert Into 插入

if(exists(select * from sys.databases where name = 'webDB'))
drop database webDB
go
--创建数据库
create database webDB on primary
(
name = 'webDB',
filename='d:\webDB.mdf',
size = 5mb,
maxsize=unlimited,
filegrowth=10%
)
log on
(
name = 'webDB_log',
filename = 'd:\webDB.ldf',
size=3mb,
maxsize=50mb,
filegrowth=2mb
) use webDB
go
--创建表
create table student(
id int identity(1,1) primary key,
name varchar(20) not null,
sex char(2) not null,
age int
) --使用Insert Into 插入一行数据
insert into student (name,sex,age) values ('白大伟','男',26)
--id为标识列 自动增长 无需为其添加值 --插入某个列
insert into student (name,sex) values ('魏力夫','妖') --如果插入全部列,可以不用写列名
insert into student values ('李东','男',37)

插入标识列Set Identity_Insert

--如果需要在标识列中插入一个值,可以使用Set Identity_Insert语句,但注意 主键不可重复!
set Identity_Insert student on --设置允许插入标识列
insert into student (id,name,sex,age) values (4,'梁不贱','男',24)
set Identity_Insert student off --插入后 关闭

使用Insert Into 插入多行数据

--使用Insert Into 插入多行数据,使用逗号分割
insert into student (name,sex,age) values
('张三','男',18),
('李四','女',19),
('王五','女',20)

使用Select语句插入

--使用Select 语句可以将现有表中的多行数据插入到目标表中
insert into student (name,sex,age) select Sname,Ssex,Sage from oldTable

使用Select Into插入

--使用Select Into 插入数据
--该方法其实是创建了一张新表,然后由select语句将所有行添加到新创建的表中。
select id,name,sex,age
into newTable
from student
--这种方式创建的表,没有主键,索引,以及约束,并且表列的长度也会发生变化。不适合创建永久表

更新数据

使用Update语句更新数据

--需要注意的是,如果不限制范围,则整表都会更新
update student set name='王大锤' where id = 3

引用多表更新数据

--有时会需要引用另外的表,用来限制更新记录
create table [user]
(
userID int identity(1,1) primary key,
userName varchar(30) not null,
passWord varchar(30) not null,
RoleId int not null
)
create table [role]
(
roleId int identity(1,1) primary key,
roleName varchar(30) not null,
roleContent varchar(50) not null
)
insert into [user] values ('admin','admin',1),('editor','editor',2),('system','system',3)
insert into [role] values ('管理员','网站管理员'),('编辑','网站编辑'),('系统','系统管理员') update [role] set roleContent = '只有user表中的用户名类似adm才会修改'
from Role r
inner join [user] u
on r.roleId = u.RoleId
where u.userName like 'adm%' --如果没有这个限制条件 则整表都更新 select * from [role]

删除数据

使用Delete删除

--如果不限制条件则整表都会被删除。
delete from student where id = 1

引用多表删除数据

--先删除user表中的admin
delete from [user] where userName = 'Admin' delete from [role]
from [role] r
left outer join [user] u
on r.roleId = u.userID
where u.RoleId is null --删除权限表中未被user表中引用的数据,管理员被删除 select * from [role]

使用truncate删除所有行

truncate table oldTable
--truncate 会删除所有行,无法指定范围.

合并数据

Merge 语句是一个多种功能的混合语句,在一个查询中可以完成Insert、Update、Delete等功能。

根据与源表联接的结果,对目标表执行插入、更新或删除操作。源表中包含即将被添加(或更新)到目标表中的数据行,而目标表接受插入(或更新)操作,可以对两个表进行同步操作。

SQL Server 2008之前的版本中是没有的,所以以前都是先删掉再添加,或写一些分支条件判断存在否 再insert 或update。

--创建源表
create table sourceTable(
id int,
content varchar(30)
) --创建目标表
create table targetTable(
id int,
content varchar(30)
) --插入测试数据
insert into sourceTable values (1,'S001'),(2,'S002'),(3,'S003'),(4,'S004'),(5,'S005')
insert into targetTable values (1,'target001'),(2,'target002'),(6,'target006'),(7,'target007') select * from sourceTable
--源表
--1 S001
--2 S002
--3 S003
--4 S004
--5 S005
select * from targetTable
--目标表
--1 target001
--2 target002
--6 target006
--7 target007 --编写merge语句
merge into targetTable t --目标表
using sourceTable s --源表
on t.id = s.id --类似join 完成两表之间的匹配
when matched --如果两表中有值被匹配,更新
then update set t.content = s.content
when not matched --如果没有匹配结果,插入
then insert values(s.id,s.content)
when not matched by source --目标表中存在但源表中不存在,删除
then delete; --再次查询,则两表同步

返回输出的数据

OUTPUT 子句可以把受影响的数据行返回给执行请求的任何接口,并且可以插入到一张表中。

OUTPUT子句可以引用inserted或deleted虚拟表,取决于需要修改前(deleted)或修改后(inserted)的数据。

输出insert语句的执行结果

insert into student
output inserted.id,inserted.name,inserted.sex,inserted.age --inserted.* 所有
select '哈哈','女',24
--返回insert语句插入的记录,对于查找服务器生成的值并返回给应用程序是很有用的。

输出update语句的执行结果

update student set name='张振'
output deleted.name as oldName,inserted.name as updateValue
where id = 4
--返回修改之前的名字 和修改之后的名字
--可以用来追踪对数据库的删除操作

将OUTPUT结果插入一张表中

--创建审计表
create table db_Audit
(
id int not null,
name varchar(50) not null,
sex varchar(50) not null,
age int,
deleteDate datetime not null
constraint DF_deleteDate_TOday default(getdate()) --默认约束 当前时间
) delete from student
output deleted.id,deleted.name,deleted.sex,deleted.age
into db_Audit(id,name,sex,age)
where id <10 -- 将id小于10的全部删除并插入到审计表中 select * from db_Audit

Merge通过output子句,可以将刚刚做过变动的数据进行输出。

merge into targetTable t    --目标表
using sourceTable s --源表
on t.id = s.id --类似join 完成两表之间的匹配
when matched --如果两表中有值被匹配,更新
then update set t.content = s.content
when not matched --如果没有匹配结果,插入
then insert values(s.id,s.content)
when not matched by source --目标表中存在但源表中不存在,删除
then delete
output $action as action,inserted.id as 插入的id,
inserted.content as 插入的内容,
deleted.id as 删除的id,
deleted.content as 删除的内容;

9、SQL Server 操作数据的更多相关文章

  1. 009.Working with SQL Server LocalDB --【在sql server localdb 上操作数据】

    Working with SQL Server LocalDB 在sql server localdb 上操作数据 2017-3-7 2 分钟阅读时长 本文内容 1.SQL Server Expres ...

  2. 腾讯云图片鉴黄集成到C# SQL Server 怎么在分页获取数据的同时获取到总记录数 sqlserver 操作数据表语句模板 .NET MVC后台发送post请求 百度api查询多个地址的经纬度的问题 try{}里有一个 return 语句,那么紧跟在这个 try 后的 finally {}里的 code 会 不会被执行,什么时候被执行,在 return 前还是后? js获取某个日期

    腾讯云图片鉴黄集成到C#   官方文档:https://cloud.tencent.com/document/product/641/12422 请求官方API及签名的生成代码如下: public c ...

  3. sql server 2008 操作数据表

    SQL Server表   表的类型:   ①临时表 临时表可用来处理中间数据或者用临时表 与其它连接共享进行中的工作.临时表只 能放在tempdb中. 私有临时表(#) 全局临时表(##)   ②系 ...

  4. sql server 日志文件结构及误操作数据找回

    一. 概述 在sql server 里有数据文件.mdf和日志文件.ldf,日志文件是sqlserver数据库的另一个重要组成部分,日志文件记录了所有事务以及每个事务对数据库所做的修改.为了提高数据库 ...

  5. SQL Server游标(转)

    清晰地介绍了SQL游标,很好的学习资料. 转自 http://www.cnblogs.com/knowledgesea/p/3699851.html 什么是游标 结果集,结果集就是select查询之后 ...

  6. SQL语句操作数据与一些函数使用的丰富数据库

    数据库有多重要,其实不用我说,但该怎么运用好数据库下SQL语句与其它的如“函数”等等,那就需要我们大家多多去练习并总结其中的窍门,或许你的总结没那么好,担只要你的练习足够多,就算那不是窍门,那也将是你 ...

  7. 数据库(SQL Server)管理数据库表~新奇之处

    说到“数据库”,我总有一种莫名的感觉,在刚刚接触到的数据库中就让我似懂非懂渡过着,于是思考着.于是在冷静的时空中让我回想到了很多的知识,不知你们是怎样过来的,真心希望我的这篇数据库总结能够让我们都有一 ...

  8. Sql Server系列:数据表操作

    表是用来存储数据和操作数据的逻辑结构,用来组织和存储数据,关系数据库中的所有数据都表现为表的形式,数据表由行和列组成.SQL Server中的数据表分为临时表和永久表,临时表存储在tempdb系统数据 ...

  9. SQL Server游标

    什么是游标 结果集,结果集就是select查询之后返回的所有行数据的集合. 游标则是处理结果集的一种机制吧,它可以定位到结果集中的某一行,多数据进行读写,也可以移动游标定位到你所需要的行中进行操作数据 ...

随机推荐

  1. Linux-awk直接修改原文件

    #注意:重定向符号后面的文件名需要加双引号 awk '{print > "file"}' file

  2. [转]require(),include(),require_once()和include_once()区别

    require(),include(),require_once()和include_once()区别 面试中最容易提到的一个PHP的问题,我想和大家共勉一下: require()和include() ...

  3. 模拟discuz发帖的类实现

    一直想弄个discuz的数据采集程序,这2天研究了下discuz发帖涉及的几个数据库表,这里分享一下自己的处理方法. discuz发表主题设计的几个表:(这里列出了主要的几个相关的表) 1.主题表 p ...

  4. KMPlayer 捆绑商业软件问题以及解决办法

    Kmplayer 本来是很好的播放软件,支持的格式很多,特别我要在本地播放flash swf 就用它.昨天下载安装了他们推荐已久的更新之后,莫名帮我安装了几个软件,都是我不能选择的,例如Winzip. ...

  5. 协程、异步IO

    协程,又称微线程,纤程.英文名Coroutine,协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器 ...

  6. MYSQL 锁机制 分析

    MySQL的表级锁有两种模式:表共享读锁(Table Read Lock)和表独占写锁(Table WriteLock).MyISAM在执行查询语句(SELECT)前,会自动给涉及的所有表加读锁,在执 ...

  7. 转 Dynamics CRM Alert and Notification JavaScript Methods

    http://www.powerobjects.com/2015/09/23/dynamics-crm-alert-and-notification-javascript-methods/ Befor ...

  8. 修改sys密码与nbu备份脚本密码后,nbu备份报密码无效

    公司要求口令强化,在修改sys密码后nbu的.sh脚本connect备份归档的sys/passwd也随之修改修改后每个业务备份均失败, 每次备份到归档那里就结束报密码无效,疑惑备份脚本密码也同步修改了 ...

  9. [DFNews] Fire-Eye与Fox IT联合推出Cryptolocker解锁网站

    Cryptolocker是臭名昭著的勒索程序,使用AES加密后密钥回传,用户除了缴纳赎金之外基本无法解密数据. 近日,知名安全公司Fire-Eye与Fox IT联合推出了针对该勒索程序的解锁网站 ht ...

  10. 转换实例存储支持为EBS支持的AMI

    转换实例存储支持为EBS支持的AMI 注:不能将实例存储支持的Windows AMI 转换为 EBS 支持的 AMI.并且,你只能转换你所拥有的 AMI. 1. 从一个EBS支持的AMI启动一个Ama ...