sql 存在更新,不存在插入

2021-09-13 11:30:33 字數 1480 閱讀 5588

1、語法

if exists (select * from users where name='張三')

print 1

else

print 0

2、建表語句

create table [dbo].[users] (

[id] int not null identity(1,1) ,

[name] varchar(50) null ,

[***] varchar(5) null )go

set identity_insert [dbo].[users] on

goinsert into [dbo].[users] ([id], [name], [***]) values (n'1', n'李四', n'女');

insert into [dbo].[users] ([id], [name], [***]) values (n'2', n'張三', n'女');

insert into [dbo].[users] ([id], [name], [***]) values (n'3', n'王五', n'男');

3、例子,存在更新,不存在插入

if exists (select * from dbo.users s where s.name='張三')

update users set ***='男' where name = '張三'

else

insert into users (name,***) values ('張三','女')

—————————————————————————————————

1、語法

replace into 表名(列名1, 列名2, ..., 列名n) values (值1, 值2, ..., 值n);
2、例子

replace into  students (stuname, stuid, class) values ('張三', '123456789', '1234567');
3、語句原理

replace into 語句要求被插入的表需要有已經定義的主鍵,該語句通過對主鍵進行檢索判斷記錄是否存在,若記錄存在,則對非主鍵屬性進行更新操作;若記錄不存在,則插入一條新記錄。

2019.1.7 更新:此處的更新操作指的是按新的資料覆蓋該主鍵標識的記錄,而不是針對某些列進行更新

4、受影響的行數

當相同主鍵記錄存在,且欲更新的資料與已存在的資料完全相同時(即此時什麼都不做),受影響的行數為 1。

當相同主鍵記錄存在,且欲更新的資料與已存在的資料不完全相同時(即此時會更新資料),受影響的行數為 2。

當相同主鍵記錄不存在時,將插入一條新的記錄,受影響的行數為 1。

mysql,存在就更新,不存在就插入

mysql 當記錄不存在時插入,當記錄存在時更新 網上基本有三種解決方法。第一種 示例一 插入多條記錄 假設有乙個主鍵為 client id 的 clients 表,可以使用下面的語句 insert into clients client id,client name,client type sel...

Mysql 批量操作,存在更新,不存在插入

在大量資料插入,但是有很多重複資料。假設有如下資料 語法如下 insert into table name clo1,col2,values val1 1,val1 2,val2 1,val2 2,val3 1,val3 2,on duplicate key update clo1 values c...

mysql存在更新不存在新增

1 插入一條資料,存在則不操作,不存在就插入 必須現有唯一鍵 使用insert ignore語句 insert ignore into table col1,col2 values a b 例如插入資料 insert ignore into user info last name,first nam...