SQL Server为计算列提供值

时间:2018-10-08 22:34:57

标签: sql sql-server

我正在尝试运行insert into语句,该语句的一列需要来自同一语句的信息。

例如:

INSERT INTO tblorders (CUST_ID, PRO_ID, QUANTITY, TOTAL)
VALUES (
    (SELECT CUST_ID FROM tblcustomer WHERE EMAIL = 'cwentz@gmail.com'),
    (SELECT PRO_ID FROM tblinventory WHERE PRO_NAME = 'Air Jordan 1'),
    1,
    ((SELECT PRICE FROM tblinventory WHERE PRO_ID = tblorders.PRO_ID) * 1)
);

在最后一个选择语句中,我试图通过获取已经在其上方选择的PRO_ID来获取“ Air Jordan 1”的价格。所以我认为这不是运行:

((SELECT PRICE FROM tblinventory WHERE PRO_NAME='Air Jordan 1') * 1)

这确实有效,我想尝试根据已从此语句中收到的PRO_ID获取价格:

(SELECT PRO_ID FROM tblinventory WHERE PRO_NAME='Air Jordan 1')

那么有什么方法可以引用您要向其中输入数据的表?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,那么您基本上希望在三个表中使用JOIN

INSERT INTO tblorders(CUST_ID, PRO_ID, QUANTITY, TOTAL)
    SELECT c.CUST_ID, i.PRO_ID, o.PRICE
    FROM tblcustomer c JOIN
         tblinventory i
         ON c.EMAIL = 'cwentz@gmail.com' AND i.PRO_NAME = 'Air Jordan 1' JOIN
         tblorders o
         ON i.PRO_ID = o.PRO_ID

答案 1 :(得分:0)

改为使用select

INSERT INTO tblorders(CUST_ID,PRO_ID,QUANTITY,TOTAL)
SELECT 
    (SELECT CUST_ID FROM tblcustomer WHERE EMAIL='cwentz@gmail.com'), 
    PRO_ID, 1 QUANTITY, PRICE
FROM tblinventory WHERE PRO_NAME='Air Jordan 1'

TOP 1或此处可能需要类似的内容。