sql insert语句加入条件判断怎么写

2024-12-04 09:54:04
推荐回答(2个)
回答1:

---不知道你说的是哪种情况,我理解的有2种,1是对插入源进行过滤,2是对插入的某些值作判断,是某个特定值时转换成另一个值

--情况1:使用Insert Into Select语法实现
--通过拼接结果集作为Select数据源之后可以加Where条件
Insert Into YourTable (id,name,status,remark)

Select id,name,status,remark From (
Select 1 as id,'张三' as name,'在职' as status,'没有备注' as remark Union Select 2,'李四','离职',''
) as s Where id>2 And id<5--条件

--情况2:给插入值作特殊判断
Insert Into YourTable (id,name,status,remark)

Select id,name,Case When status='在职' Then 1 WHen status='离职' Then 2 Else 0 End,remark From (
Select 1 as id,'张三' as name,'在职' as status,'没有备注' as remark Union Select 2,'李四','离职',''
) as s

回答2:

where子句,将各条件用and或or连接