为什么我的自动增量在SQL Server 2008中不起作用?

时间:2014-05-20 17:05:11

标签: sql database sql-server-2008 datatable

这是我创建的表格:

create table Movie 
(
     MovieID int NOT NULL IDENTITY (1,1) PRIMARY KEY, 
     MovieName varchar(40) NOT NULL UNIQUE, 
     CurrentStock int NOT NULL, 
     GenreID int NOT NULL,
     RatingID int NOT NULL, 
     Max_Inventory int NOT NULL, 
     Platforms char(5) NOT NULL, 
     Discontinued bit, 
     DiscontinuedDate Date
); 

create table Inventory
(
     InventoryID int NOT NULL IDENTITY (1,1) PRIMARY KEY, 
     MovieID int Not NULL,
     CurrentStock int NOT NULL, 
     Max_Inventory int NOT NULL
);

存储过程:

ALTER PROCEDURE [dbo].[InsInventory]
(@CurrentStock int,
 @ChangeStock int)
as
begin
  insert into Inventory(Max_Inventory, CurrentStock)
  Values (@ChangeStock, @CurrentStock)

  select SCOPE_IDENTITY();
END

ALTER PROCEDURE [dbo].[InsMovie] 
(@GenreID int,
 @RatingID int,
 @Platform varchar(5),
 @MovieName varchar(40)
)
AS
BEGIN
   Insert into Movie (RatingID, MovieName, Platforms, GenreID)
   Values (@RatingID, @MovieName, @Platform, @GenreID)

   select SCOPE_IDENTITY();

   SET NOCOUNT ON;
END

外键:

ALTER Table Inventory
ADD CONSTRAINT fk_Inventory_Movie 
FOREIGN KEY (MovieID) REFERENCES Movie(MovieID)

ALTER TABLE Movie
ADD CONSTRAINT fk_Movie_RatingLookUp
FOREIGN KEY (RatingID) REFERENCES RatingLookUp(RatingID)

ALTER TABLE Movie
ADD CONSTRAINT fk_Movie_GenreLookUp
FOREIGN KEY (GenreID) REFERENCES GenreLookUp (GenreID)

当我运行我的代码时,我一直在Visual Studio中收到错误

  

MovieID不能为空

但是我应该插入一行。我还确保手动检查SQL Server是否设置了IsIdentity。所以请帮助一个困惑的程序员。

2 个答案:

答案 0 :(得分:2)

您不应该将NULL作为主键插入以使其生成值,您应该根本不插入该值,方法是不在要插入的字段中列出该值。作为样本;

INSERT INTO Movie (moviename, currentstock, genreid, ratingid, max_inventory, platforms)
                  VALUES ('name1', 1, 1, 1, 1, '1');

A simple working sample with your exact table creation

答案 1 :(得分:0)

下面的陈述是你的问题。你的表def显示MovieID不为空。但在下面的陈述中你没有提供。

insert into Inventory(Max_Inventory, CurrentStock)
Values (@ChangeStock, @CurrentStock)

这是你需要做的事情..首先你需要检索将从执行InsMovie sproc返回的Movie id。比你需要使用那个Movie Id作为InsInvetory sproc调用的参数。

根据您的表格def电影ID是必需的。同样对于Movie表,你错过了我添加的两个列值,这些值也是必需的。

请参阅打击更新的存储过程。

ALTER PROCEDURE [dbo].[InsInventory]
(

@CurrentStock int,
@ChangeStock int,
@MovieID int
)

as
begin
insert into Inventory(MovieID, Max_Inventory,CurrentStock)
    Values (@MovieID, @ChangeStock, @CurrentStock)

select SCOPE_IDENTITY();
END

ALTER PROCEDURE [dbo].[InsMovie] 
(
@GenreID int,
@RatingID int,
@Platform varchar(5),
@MovieName varchar(40),
@CurrentStock int, 
@max_inventory int
)
AS
BEGIN

Insert into Movie (CurrentStock, max_inventory, RatingID, MovieName, Platforms,GenreID)
    Values(@CurrentStock, @max_inventory, @RatingID,@MovieName, @Platform, @GenreID)

select SCOPE_IDENTITY();

SET NOCOUNT ON;


END