我有tabA:
________________________
|ID |EMPLOYEE|CODE |
|49 |name1 |mobile |
|393 |name2 |none |
|3002|name3 |intranet|
________________________
ID列(tabA)基于下面tabB中的计数器:
_________________
|TYPE |ID |
|intranet |3003|
|mobile |50 |
|none |394 |
__________________
我想使用ID计数器在tabA中插入新行(因为它是下一个可用的ID)。如何根据计数器值插入表格?
我正在尝试此方法,导致尝试插入重复类型,而不是max(ID):
INSERT INTO tabA (ID, EMPLOYEE, CODE)
VALUES ((select max(ID) from tabB where TYPE = 'A'),name4,'intranet');
我希望看到tabA:
________________________
|ID |EMPLOYEE|CODE |
|3000|name1 |mobile |
|3001|name2 |none |
|3002|name3 |intranet|
|3003|name4 |intranet|
________________________
塔布:
_________________
|TYPE |ID |
|mobile |2999|
|none |3002|
|intranet |3004|
__________________
答案 0 :(得分:1)
我建议以下答案:
@tabA和@tabB我假设你的是tabA和tabB。
declare @tabA table
(
id integer,
employee nvarchar(10),
code nvarchar(10)
)
insert into @tabA values (49, 'name1','mobile');
insert into @tabA values (393, 'name2','none');
insert into @tabA values (3002, 'name3','intranet');
declare @tabB table
(
type_ nvarchar(10),
ID integer
)
insert into @tabB values ('intranet',3003);
insert into @tabB values ('mobile',50);
insert into @tabB values ('none', 394);
insert into @tabA
select MAX(b.ID), 'name4','intranet'
from @tabB B
where b.type_ = 'intranet'
declare @max integer
select @max = MAX(ID) from @tabB where type_ = 'intranet'
declare @max_1 integer
set @max_1 = @max + 1
update @tabB
set ID = @max_1
from @tabB B
where type_ = 'intranet'
select * from @tabA
select * from @tabB
----------------------------
what I got from @tabA
49 |name1| mobile
393 |name2| none
3002 |name3| intranet
3003 |name4| intranet
what I got from @tabB
intranet|3004
mobile |50
none |394
答案 1 :(得分:0)
使用insert . . . select
:
INSERT INTO tabA(ID, EMPLOYEE, CODE)
select max(ID), 'name4', 'intranet'
from tabB
where TYPE = 'A';
答案 2 :(得分:0)
这将解决您的问题:(假设您的ID是增量的)
INSERT INTO tabA (ID, EMPLOYEE, CODE)
VALUES ((SELECT TOP 1 ID + 1 FROM tabA ORDER BY ID DESC),'name4', 'intranet')