我有一张这样的表:
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”。
我做错了什么?
答案 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