我正在尝试将子查询的结果插入到表中,但我要插入的表具有唯一的主ID。我想取EID编号的最大值,并在我试图插入表格的任何条目中加1。
表格我要插入:
----------------------------------------------------
EID (pk) | First Name | Employment Date
----------------------------------------------------
1 | John | 2016-01-01
2 | Joe | 2013-01-01
3 | Jill | 2012-01-01
4 | Jen | 2017-01-01
我的子查询声明:
(SELECT FIRSTNAME, ORDERDATE as EMPLOYMENTDATE
FROM CUSTOMER, ORDER
WHERE CUSTOMER.id = ORDER.id
AND ORDERDATE >= DATE '2017-01-01')
问题是插入,因为我没有唯一的ID来生成。这是在SQL Server上
我想插入这样的东西:
INSERT INTO EMPLOYEE(EID, FIRSTNAME, EMPLOYMENTDATE)
SELECT ??????WHAT GOES HERE??????, FIRSTNAME, ORDERDATE as EMPLOYMENTDATE
FROM CUSTOMER, ORDER
WHERE CUSTOMER.id = ORDER.id
AND ORDERDATE >= DATE '2017-01-01'
答案 0 :(得分:0)
假设EID是身份,这就是:
INSERT INTO EMPLOYEE(FIRSTNAME, EMPLOYMENTDATE)
SELECT FIRSTNAME, ORDERDATE as EMPLOYMENTDATE
FROM CUSTOMER, ORDER
WHERE CUSTOMER.id = ORDER.id
AND ORDERDATE >= DATE '2017-01-01'
答案 1 :(得分:0)
你是对的,因为你正在使用子查询,它会是这样的:
INSERT INTO EMPLOYEE(EID, FIRSTNAME, EMPLOYMENTDATE)
SELECT
ISNULL((MAX(Emp.EID)+1),1) AS EID,
CustOrd.FirstName,
CustOrd.EmploymentDate
FROM
EMPLOYEE Emp,
(SELECT FIRSTNAME, ORDERDATE as EMPLOYMENTDATE
FROM CUSTOMER, ORDER
WHERE CUSTOMER.id = ORDER.id
AND ORDERDATE >= DATE '2017-01-01') CustOrd