SQL Server 插入记录前判断是否存在,不存在则插入,存在则修改,不采用触发器​

SQL Server 插入记录前判断是否存在,不存在则插入,存在则修改,不采用触发器

IF EXISTS(SELECT * FROM sysobjects WHERE [name]='Users')
	DROP TABLE [Users]
GO
CREATE TABLE [Users](
		[Id] [int] IDENTITY (1,1) PRIMARY KEY([Id]),
		[UserName] [nvarchar](50),
		[Sex] [nvarchar](2)
);
GO

--如果不存在admin用户则新建, 存在则更新
if NOT EXISTS(SELECT * FROM [Users] WHERE [UserName]='admin')
	INSERT INTO Users([UserName],[Sex])VALUES('admin','男')
ELSE 
	UPDATE [Users] SET [Sex]='女' WHERE [UserName]='admin';

SELECT* FROM [Users];


热门推荐