如何将主键列的值添加到其他表的外键列中:我使用SQL Server 2012
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL,
ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID));
CREATE TABLE ORDERS ( ID INT NOT NULL, DATE DATETIME, CUSTOMER_ID INT references
CUSTOMERS(ID), AMOUNT VARCHAR (255), PRIMARY KEY (ID));
在这里,我需要从主键表'客户'中获取所有值。来自专栏' ID'到外键表订单到列' ID'
DECLARE @A INT, @DATE DATETIME, @C_ID INT, @AMOUNTS INT;
SET @A =1;
SET @DATE ='2009-10-08 00:00:00';
SET @C_ID = 100
SET @AMOUNTS=1000;
WHILE @A <= 7
BEGIN
SET @DATE = DATEADD(DAY,1,@DATE);
SET @C_ID = @C_ID + 1
SET @AMOUNTS = @AMOUNTS+100;
INSERT INTO ORDERS(ID, DATE, CUSTOMER_ID,AMOUNT)
SELECT ID, @DATE, @C_ID, @AMOUNTS FROM CUSTOMERS WHERE AGE like'%';
SET @A = @A+1;
END
答案 0 :(得分:1)
您已使用引用Customers(ID)的Customer_ID上的外键设置Orders表。因此,如果客户中存在ID,您只能向订单添加行。现在,您每次尝试在该列中插入101-107,因此请检查客户中是否存在这些ID。
在我看来,您应该想要在Orders.Customer_ID中插入Customers.ID列,而不是Orders.ID。那是你的意思吗?