插入语句中的SQL Select

时间:2019-01-30 17:47:16

标签: sql

如何结合这两个脚本?我基本上不想将数字34硬编码在Query 2中。我希望脚本采用下一个job_id。 Query 1返回34,因此Query 2应该以{{1​​}}作为35

查询1

job_id

查询1的输出-34

查询2

select top 1 job_id from job
order by job_id desc

4 个答案:

答案 0 :(得分:2)

您可以通过将job_id定义为identity列来做到这一点:

create table jobs (
     job_id int identity(1, 1) primary key,
     name varchar(255)
);

然后您可以做:

insert into jobs (name)
    values ('Defend them');

然后SQL Server分配作业ID。

答案 1 :(得分:0)

怎么样?

insert into job (job_id, name)
select top 1 job_id+1, 'Defend them'
from job
order by job_id desc

答案 2 :(得分:0)

select     top 1 job_id, 'Defend them' 
into       job (job_id, name)
from       job
order by   job_id DESC

答案 3 :(得分:0)

无需使用order by job_id desctop 1来获取所需的值。
您需要max(job_id) + 1

insert into job (job_id, name)
select max(job_id) + 1, 'Defend them'
from job