不能在id列中插入null值

时间:2014-11-30 07:55:28

标签: sql-server

我试图将数据插入medicine + Stock表。

但它通过错误无法将空值插入列id表medicalstore.dbo.stock

以下是我的疑问:

query = "Insert Into Medicine (Code,Name,CompanyID,UnitPrice,CategoryID) Values ('" & row.Cells("MedCode").Value & "','" & row.Cells("MedName").Value & "','" & row.Cells("MedCompID").Value & "','" & row.Cells("MedPrice").Value & "','" & row.Cells("MedCatID").Value & "')"
query1 =   "Insert Into Stock(MedicineID,AvailableQuantity) Values('2338','10')"

这是我的表结构。

Create table medicine
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Code] [nchar](10) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [CompanyID] [int] NOT NULL,
    [UnitPrice] [varchar](15) NOT NULL,
    [ExpiryDate] [datetime] NOT NULL,
    [CategoryID] [int] NOT NULL,

    CONSTRAINT [ID_Medicine] PRIMARY KEY CLUSTERED 
)

CREATE TABLE [dbo].[Stock]
(
    [ID] [int] NOT NULL,
    [MedicineID] [int] NOT NULL,
    [AvailableQuantity] [bigint] NOT NULL,

    CONSTRAINT [Stock_ID] PRIMARY KEY CLUSTERED 
    CONSTRAINT [FK_Stock_Medicine] FOREIGN KEY([MedicineID])
      REFERENCES [dbo].[Medicine] ([ID])
)

以下是我自己输入StockID时得到的结果

Here is what I get when I enter StockID by myself

2 个答案:

答案 0 :(得分:2)

您在库存表

中指定了Not Null
[ID] [int] NOT NULL

然后您必须在插入时指定其ID,并且整数不需要单引号

query1 =   "Insert Into Stock(ID,MedicineID,AvailableQuantity) Values(1,2338,10)"

您可以更改表定义类似于此内容

CREATE TABLE [dbo].[Stock](
[ID] [int] [int] IDENTITY(1,1) NOT NULL,
[MedicineID] [int] NOT NULL,
[AvailableQuantity] [bigint] NOT NULL,
CONSTRAINT [Stock_ID] PRIMARY KEY CLUSTERED 
CONSTRAINT [FK_Stock_Medicine] FOREIGN KEY([MedicineID])
REFERENCES [dbo].[Medicine] ([ID])
)

然后尝试这样:

 query1 =   "Insert Into Stock(MedicineID,AvailableQuantity) Values(2338,10)"

答案 1 :(得分:0)

您应该自己插入Stock.ID或为Stock.ID指定IDENTITY(1,1)