将数据从主表中插入temp1表,其中temp 1中的记录不在temp2中

时间:2017-09-08 15:15:42

标签: sql sql-server

我已经创建了下面的代码,通过从主表中选择前500行来向temp表添加数据。检查temp1在temp2中没有匹配的记录,但我似乎可以让它工作。

create table #temp1 (
int_code int,product varchar (10),
vchr_product name varchar (100),
vchr_productgrouplist varchar (max)
vchr_disabledcapabilities varchar (500),
vchr_services varchar (100))

create table #temp2 ( int_code int)

INSERT INTO #temp2

SELECT [int_code]
FROM dbo.tbl_maintable

这是我无法做到的地方:

Insert into #temp1
select top 500 
int_code,
vchr_product name,
vchr_productgrouplist,
vchr_services
from dbo.tbl_maintable 
where #temp2.int_code not in (select int_code form #temp1)

非常感谢任何帮助或建议。

1 个答案:

答案 0 :(得分:0)

您的WHERE子句需要将源表中的值与#temp2表中的值进行比较。尝试比较目标表(#temp1)中的值并没有什么意义,因为它们尚未插入。所以,

INSERT INTO #temp1 (
    int_code,
    vchr_product name,
    vchr_productgrouplist,
    vchr_services
)
SELECT TOP 500 
    int_code,
    vchr_product name,
    vchr_productgrouplist,
    vchr_services
FROM dbo.tbl_maintable 
WHERE int_code NOT IN (SELECT int_code FROM #temp2)

另请注意,您需要列列表作为INSERT INTO(...)的一部分,因为您不希望将tbl_maintable.vchr_services值插入#temp1.vchr_disabledcapabilities