尝试仅将唯一行插入新表中

时间:2012-05-09 16:53:38

标签: sql-server tsql

我试图只将唯一值插入表中但它不起作用。对于所有6000行,在Securities表中只有一个LastDownload值。但在我的查询中,我在@Temp中获得了超过6000个重复值。我只想要一个价值。我错过了什么?

DECLARE @Temp TABLE ( Info VARCHAR( 256 ) )

INSERT INTO @Temp
SELECT LastDownLoad
FROM Securities AS S
WHERE NOT EXISTS( SELECT * FROM @Temp AS T WHERE T.Info = S.LastDownLoad ) 

3 个答案:

答案 0 :(得分:2)

也许这过于简单......但......似乎适合......

DECLARE @Temp TABLE ( Info VARCHAR( 256 ) )

    INSERT INTO @Temp
    SELECT Distinct LastDownLoad
    FROM Securities

答案 1 :(得分:2)

将两个答案放在一起,你得到完整的答案:

DECLARE @Temp TABLE ( Info VARCHAR( 256 ) )

INSERT INTO @Temp
SELECT DISTINCT LastDownLoad
FROM Securities AS S
WHERE NOT EXISTS( SELECT * FROM @Temp AS T WHERE T.Info = S.LastDownLoad ) 

答案 2 :(得分:1)

您是否尝试使用distinct

DECLARE @Temp TABLE ( Info VARCHAR( 256 ) )

INSERT INTO @Temp
SELECT LastDownLoad
FROM Securities AS S
WHERE NOT EXISTS( SELECT DISTINCT * FROM @Temp AS T WHERE T.Info = S.LastDownLoad )