【问题标题】:SQL Server 2012 sequenceSQL Server 2012 序列
【发布时间】:2012-10-05 11:13:06
【问题描述】:

我创建了一个表和序列以替换表中的标识我使用 SQL Server 2012 Express,但是当我尝试向表中插入数据时出现此错误

消息 11719,第 15 层,状态 1,第 2 行
检查约束、默认对象、计算列、 视图、用户定义的函数、用户定义的聚合、用户定义的 表类型、子查询、公用表表达式或派生表 表格。

T-SQL 代码:

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

这是我的桌子:

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)
);

这是我的顺序:

CREATE SEQUENCE [dbo].[Job_Log_Update_SEQ] 
 AS [int]
 START WITH 1
 INCREMENT BY 1
 NO CACHE 
GO

【问题讨论】:

    标签: sql sql-server tsql sequences sql-server-2012-express


    【解决方案1】:

    只需去掉 VALUES 部分中的子选择,如下所示:

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

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

    【讨论】:

      【解决方案2】:

      您的插入语法似乎有误。您正在尝试在查询的 VALUES 部分中使用 SELECT 语句。如果你想使用SELECT,那么你将使用:

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

      SQL Fiddle with Demo

      我将语法从 INSERT INTO VALUES 更改为 INSERT INTO ... SELECT。我使用它是因为您正在选择序列的下一个值。

      但是,如果您想使用 INSERT INTO.. VALUES,则必须从查询中删除 SELECT

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

      SQL Fiddle with Demo

      这两个都将INSERT的记录放入表中。

      【讨论】:

        【解决方案3】:

        试试这个:


        –带一张桌子

        创建序列idsequence 以 1 递增 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;
        
        ------------------------------
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-06-16
          • 1970-01-01
          • 2014-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-16
          相关资源
          最近更新 更多