SQL存储过程WHERE项不在表中

时间:2016-02-02 15:28:30

标签: sql sql-server tsql stored-procedures

我有一张这样的表:

DECLARE @deadCommunityList TABLE (community VARCHAR(12))
INSERT INTO @deadCommunityList (community)
VALUES ('000')
    , ('253'), ('COU'), ('COV')
    , ('D2T'), ('D3T'), ('DEW')
    , ('DIT'), ('E2T'), ('E3T')
    , ('EL2'), ('EL3'), ('ELC')
    , ('ELI'), ('ELT'), ('ERI')
    , ('FA1'), ('GRA'), ('GRD')
    , ('GRT'), ('HIG'), ('HIP')
    , ('LYN'), ('NEW'), ('PAR')
    , ('PMT'), ('RDT'), ('RES')
    , ('SCR'), ('SCT'), ('SMT')
    , ('SUM'), ('TB'), ('W2T')
    , ('WDV'), ('WE2'), ('WIC')
    , ('WEC'), ('WIL'), ('ZIT')

现在我有这样的查询:

SELECT DISTINCT AREA_DESC
FROM V_CONSTAT_PROJ_DATES
WHERE AREA_ID NOT IN @deadCommunityList
ORDER BY AREA_DESC

我想说的是给我结果,其中AREA_ID不在表格中....这不起作用,我得到以下错误:

  

必须声明标量变量“@deadCommunityList”。

我做错了什么?

3 个答案:

答案 0 :(得分:5)

试试这个:

SELECT DISTINCT AREA_DESC 
FROM V_CONSTAT_PROJ_DATES 
WHERE AREA_ID NOT IN (SELECT community FROM @deadCommunityList)
ORDER BY AREA_DESC

@deadCommunityList变量,因此您必须从其值中SELECT

答案 1 :(得分:3)

DECLARE @deadCommunityList TABLE (
    community VARCHAR(12) PRIMARY KEY --WITH (IGNORE_DUP_KEY=ON)
)

INSERT INTO @deadCommunityList
...

SELECT DISTINCT AREA_DESC
FROM V_CONSTAT_PROJ_DATES
WHERE AREA_ID NOT IN (SELECT e.community FROM @deadCommunityList е)
ORDER BY AREA_DESC
--OPTION(RECOMPILE)

答案 2 :(得分:1)

您应该在where条件中使用subselect,因为@deadCommunityList是表变量。

SELECT DISTINCT AREA_DESC 
FROM V_CONSTAT_PROJ_DATES 
WHERE AREA_ID NOT IN (select community from @deadCommunityList)
ORDER BY AREA_DESC

或者,您可以加入此表变量并仅获取V_CONSTAT_PROJ_DATES中与@deadCommunityList没有匹配记录的记录:

SELECT DISTINCT T.AREA_DESC 
FROM V_CONSTAT_PROJ_DATES as T
    left outer join @deadCommunityList as T1 on T1.community = T.AREA_ID
WHERE T1.community is null
ORDER BY T.AREA_DESC