操作数据(insert、update、delete)

插入数据

使用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 删除的内容;

时间: 2024-08-08 10:32:05

操作数据(insert、update、delete)的相关文章

数据库编程3 Oracle 子查询 insert update delete 事务 回收站 字段操作 企业级项目案例

[本文谢绝转载原文来自http://990487026.blog.51cto.com] <大纲> 数据库编程3 Oracle 子查询 insert update delete 事务 回收站 字段操作 企业级项目案例 实验所用数据表 子查询,解决一步不能求解 查询工资比scott高的员工信息: 子查询知识体系搭建: 解释3,查询部门是sales的员工信息: 方法1:子查询 [方法2]:多表: 优化考虑: 解释4[select],只能放单行子查询 解释4[from] 考题:显示员工姓名,薪水 解释

LINQ体验(9)——LINQ to SQL语句之Insert/Update/Delete操作

我们继续讲解LINQ to SQL语句,这篇我们来讨论Insert/Update/Delete操作.这个在我们的程序中最为常用了.我们直接看例子. Insert/Update/Delete操作 插入(Insert) 1.简单形式 说明:new一个对象,使用InsertOnSubmit方法将其加入到对应的集合中,使用SubmitChanges()提交到数据库. NorthwindDataContext db = new NorthwindDataContext(); var newCustomer

linux下mysql Insert update delete 事务 用户管理

linux下mysql Insert update delete  事务 用户管理 1.INSERT插入语句格式: INSERT INTO tb_name (字段1, 字段2, ...) VALUES (值1,值2, ...)[,(值1, 值2, ...),...]; INSERT INTO 表名 SET 字段1=值1,字段2=值2,...; INSERT INTO 表名 (字段1,字段2,...) SELECT (字段1,字段2,...) FROM 表名 [WHERE 条件]; 2.REPLA

mybatis insert update delete返回都是整型 0,1,增,删,改要提交事物

mybatis insert update delete返回都是整型 0,1, 没有扔 增,删,改要提交事物 原文地址:https://www.cnblogs.com/gzhbk/p/9499293.html

元素类型为 &quot;mapper&quot; 的内容必须匹配 &quot;(cache-ref|cache|resultMap*|parameterMap*|sql*|insert*|update*|delete*|select)

在配置ssm框架的时候,写mapper映射文件的时候会出现 元素类型为 "mapper" 的内容必须匹配 "(cache-ref|cache|resultMap*|parameterMap*|sql*|insert*|update*|delete*|select) 有时候编译的时候会出现这个bug,是因为在前面写了注释.导致了执行顺序的问题.需要把一些注释删掉,就可以正常执行了. /*mapper动态开发*/ <mapper namespace="com.ss

数据库--MyBatis的(insert,update,delete)三种批量操作

转自:http://blog.csdn.net/starywx/article/details/23268465 前段时间由于项目赶期没顾上开发过程中的性能问题,现对部分代码进行优化的过程中发现在数据量大的情况下对数据的操作反应似乎有些慢,就想到对数据库DML操作的时候进行批量操作.说道这里也想到自己在一次面试的时候别问道过批量操作数据的问题. 现对运用说明记录如下: 批量插入insert 方法一: <insert id="insertbatch" parameterType=&

mysql之insert,update,delete

测试数据 1.product表 CREATE table product( id INT(10) PRIMARY KEY NOT NULL, name VARCHAR(20) NOT NULL, function VARCHAR(50) DEFAULT NULL , company VARCHAR(20) NOT NULL, address VARCHAR(50) DEFAULT NULL ); 1.medicine表 CREATE table medicine( id INT(10) PRIM

MySQL之DML语句(insert update delete)

DML主要针对数据库表对象的数据而言的,一般DML完成: 插入新数据 修改已添加的数据 删除不需要的数据 1.insert into插入语句 //主键自增可以不插入,所以用null代替 insert into temp values(null, 'jack', 25); //指定列 insert into temp(name, age) values('jack', 22); 在表面后面带括号,括号中写列名,values中写指定列名的值即可.当省略列名就表示插入全部数据,注意插入值的顺序和列的顺

[转]NHibernate之旅(5):探索Insert, Update, Delete操作

本节内容 操作数据概述 1.新建对象 2.删除对象 3.更新对象 4.保存更新对象 结语 操作数据概述 我们常常所说的一个工作单元,通常是执行1个或多个操作,对这些操作要么提交要么放弃/回滚.想想使用LINQ to SQL,一切的东西都在内存中操作,只有调用了DataContext.SubmitChanges()方法才把这些改变的数据提交到数据库中,LINQ to SQL那么提交要么回滚. 我们使用NHibernate也一样,如果只查询数据,不改变它的值,就不需要提交(或者回滚)到数据库. 注意

Entity Framework with MySQL 学习笔记一(insert,update,delete)

先说说 insert 吧. 当EF执行insert时,如果我们传入的对象是有关联(1对多等)的话,它会执行多个语句 insert到多个表, 并且再select出来填充我们的属性(因为有些column默认值是sql设定的,比如id等,我们insert后要有最新的数据丫). using (EFDB db = new EFDB()) { db.prods.Add(new Prod { code = "mk100", name = "name", detail = new