SQL Server 2012 sequence
Asked Answered
M

3

13

I create a table and sequence in order to replace identity in the table I use SQL Server 2012 Express but I get this error while I tried to insert data to the table

Msg 11719, Level 15, State 1, Line 2
NEXT VALUE FOR function is not allowed in check constraints, default objects, computed columns, views, user-defined functions, user-defined aggregates, user-defined table types, sub-queries, common table expressions, or derived tables.

T-SQL code:

insert into Job_Update_Log(log_id, update_reason, jobid) 
values((select next value for Job_Log_Update_SEQ),'grammer fixing',39);

This is my table:

create table Job_Update_Log
(
   log_id int primary key  ,
   update_reason nvarchar(100) ,
   update_date date default getdate(),
   jobid bigint not null,
   foreign key(jobid) references jobslist(jobid)
);

and this is my sequence:

CREATE SEQUENCE [dbo].[Job_Log_Update_SEQ] 
 AS [int]
 START WITH 1
 INCREMENT BY 1
 NO CACHE 
GO
Multiphase answered 5/10, 2012 at 11:13 Comment(0)
W
25

Just get rid of the subselect in the VALUES section, like this:

insert into Job_Update_Log(log_id,update_reason,jobid) 
        values (next value for Job_Log_Update_SEQ,'grammer fixing',39);

Reference: http://msdn.microsoft.com/en-us/library/hh272694%28v=vs.103%29.aspx

Whitley answered 5/10, 2012 at 11:20 Comment(0)
P
8

Your insert syntax appears to be wrong. You are attempting to use a SELECT statement inside of the VALUES section of your query. If you want to use SELECT then you will use:

insert into Job_Update_Log(log_id,update_reason,jobid) 
select next value for Job_Log_Update_SEQ,'grammer fixing',39;

See SQL Fiddle with Demo

I changed the syntax from INSERT INTO VALUES to INSERT INTO ... SELECT. I used this because you are selecting the next value of the sequence.

However, if you want to use the INSERT INTO.. VALUES, you will have to remove the SELECT from the query:

insert into Job_Update_Log(log_id,update_reason,jobid) 
values(next value for Job_Log_Update_SEQ,'grammer fixing',39);

See SQL Fiddle with Demo

Both of these will INSERT the record into the table.

Pairs answered 5/10, 2012 at 11:16 Comment(0)
S
0

Try this one:


–With a table

create sequence idsequence start with 1 increment by 3

create table Products_ext
(
id int,
Name varchar(50)
);

INSERT dbo.Products_ext (Id, Name)
VALUES (NEXT VALUE FOR dbo.idsequence, ‘ProductItem’);

select * from Products_ext;


/* If you run the above statement two types, you will get the following:-

1    ProductItem
4    ProductItem

*/

drop table Products_ext;
drop sequence idsequence;

------------------------------
Skricki answered 16/11, 2012 at 19:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.