sql insert 内容中,部分为查询的结果

背景:

生产数据库要加入一些数据,包含有表之间关联的数据。如果用代码就很容易,但由于某些项目坑的原因,只能用脚本……

普通插入时,我们只能:

insert into Zd(userId,url,others)values('id','aaaaa',‘others...’)

是写死的数据。但有时我们需要插入“动态”数据,即某些数据是查询结果,而某些数据是写死的,就可以写成这样:

insert into Zd(userId , url, others)
select top 1 id , 'aaaaa', 'others...'
from userInfo

即把写死的数据按顺序用逗号分隔加到 from 前。下面这条也是同样的效果:

insert into Zd(url, userId , others)
select top 1 'aaaaa', id , 'others...'
from userInfo

另外值得注意的是,若插入的查询语句(比如写成select top 2 id),查出来的是多条数据,最后也会插入多条数据。

猜你喜欢

转载自my.oschina.net/u/860267/blog/835625