MS SQL:来自另一个表的INSERT值和来自常量数据的值

时间:2014-06-19 14:20:20

标签: sql sql-server

我正在尝试将值插入名为EMPLOYEE_PROGRAM_LEVEL的表中。以下是我需要指定的列名:

EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS

在插入之前,我只知道员工姓名和程序名称。 LEVEL和MANAGE_ACCESS是我需要在查询中进行硬编码的已知常量。

问题是:我需要获取与员工姓名相对应的id和与程序名对应的id,但我还需要在同一个查询中插入常量值!

我试过了:

INSERT INTO EMPLOYEE_PROGRAM_LEVEL(EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS)

SELECT ID, ID_PROGRAM FROM EMPLOYEE T1
INNER JOIN PROGRAM T2 ON T2.NOM='programName'
WHERE T1.USERNAME='userName'

VALUES(ID, ID_PROGRAM, '9000', 'O');

'9000'和'O'是固定值(LEVEL和MANAGE_ACCESS列) 显然,我不能在阻塞我的INSERT SELECT QUERY中使用VALUES。这是我得到的错误:

Incorrect syntax near the keyword 'VALUES'.

我该怎么办?

3 个答案:

答案 0 :(得分:3)

这应该适合你:

INSERT INTO EMPLOYEE_PROGRAM_LEVEL(EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS)
SELECT ID, ID_PROGRAM,'9000', 'O' 
FROM EMPLOYEE T1
INNER JOIN PROGRAM T2 ON T2.NOM='programName'
WHERE T1.USERNAME='userName'

答案 1 :(得分:2)

你几乎就在那里,只需要将常量添加到SELECT:

INSERT INTO EMPLOYEE_PROGRAM_LEVEL(EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS)
SELECT ID, ID_PROGRAM, '9000', 'O'
FROM EMPLOYEE T1
INNER JOIN PROGRAM T2 ON T2.NOM='programName'
WHERE T1.USERNAME='userName'

答案 2 :(得分:-1)

避免完整表的内部连接。仅加入过滤后的数据集,因为它可以提高性能

因此,结果应如下所示:

INSERT INTO EMPLOYEE_PROGRAM_LEVEL(EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS)
SELECT ID, ID_PROGRAM,'9000', 'O' 
FROM (SELECT * FROM EMPLOYEE WHERE USERNAME='userName') as T1
INNER JOIN (SELECT * FROM PROGRAM WHERE NOM='programName') as T2 ON 1 = 1

增加:

此外,如果您有任何具有相同名称的程序或员工,则可以避免数据重复。它可以由TOP执行。见样本:

INSERT INTO EMPLOYEE_PROGRAM_LEVEL(EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS)
SELECT ID, ID_PROGRAM,'9000', 'O' 
FROM (SELECT TOP 1 * FROM EMPLOYEE WHERE USERNAME='userName') as T1
INNER JOIN (SELECT TOP 1 * FROM PROGRAM WHERE NOM='programName') as T2 ON 1 = 1

还有一个技巧:如果找到重复项,您可以指定脚本应该记录哪条记录。假设您有每个员工的技能等级,它定义了所请求员工的优先级。另外,假设你有程序的优先级字段为程序做同样的事情。在这种情况下,您可以使用订单。见例:

INSERT INTO EMPLOYEE_PROGRAM_LEVEL(EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS)
SELECT ID, ID_PROGRAM,'9000', 'O' 
FROM (SELECT TOP 1 * FROM EMPLOYEE WHERE USERNAME='userName' ORDER BY skillLevel DESC) as T1
INNER JOIN (SELECT TOP 1 * FROM PROGRAM WHERE NOM='programName' ORDER BY priority DESC) as T2 ON 1 = 1

如果最小值定义了最高优先级,则使用ASC