假设我有一个像这样的结构表
CREATE TABLE Printout
(
ID INT ,
TypeID INT ,--TypeID references Type table
PrintoutNumber INT
)
CREATE TABLE [Type] ( ID INT, Code NVARCHAR(5) )
和两个序列
CREATE SEQUENCE FirstSequence
START WITH 1
INCREMENT BY 1 ;
CREATE SEQUENCE SecondSequence
START WITH 1
INCREMENT BY 1 ;
我想要做的是在插入行之前通过调用NEXT VALUE FOR,根据Printout表中的TypeID值将序列添加为PrintoutNumber的默认值。
例如:
IF TypeID = 1 - > PrintoutNumber = FirstSequence的下一个值
IF TypeID = 2 - > PrintoutNumber =下一个值为SecondSequence
代码:
CASE
WHEN TypeID = 1
THEN NEXT VALUE FOR dbo.FirstSequence
ELSE NEXT VALUE FOR dbo.SecondSequence
END AS PrinutoutNumber
可以使用哪种方法/方法来确定相同的结果?
感谢任何帮助
答案 0 :(得分:0)
create procedure printout_insert
(
@id int,
@TypeId int
)
as
declare @printNumber int;
if @TypeId = 1
begin
set @printNumber = NEXT VALUE FOR dbo.FirstSequence;
end;
else if @TypeId = 2
begin
set @printNumber = NEXT VALUE FOR dbo.SecondSequence;
end;
insert into printout
(
id,
TypeId,
PrintoutNumber
)
values
(
@id,
@TypeId,
@printNumber
)
- 插入行
exec printout_insert 1,1
exec printout_insert 1,2
exec printout_insert 1,1
exec printout_insert 1,2
exec printout_insert 1,1
exec printout_insert 1,2
exec printout_insert 1,1
exec printout_insert 1,2
exec printout_insert 1,1
exec printout_insert 1,2
exec printout_insert 1,1
exec printout_insert 1,2
exec printout_insert 1,1
select * from printout order by typeid, PrintoutNumber
- 结果 1 1 1 1 1 2 1 1 3 1 1 4 1 1 5 1 1 6 1 1 7 1 2 1 1 2 2 1 2 3 1 2 4 1 2 5 1 2 6