Create an inline SQL table on the fly (for an excluding left join)

跟風遠走 提交于 2019-11-28 19:14:24

You can create an "inline table" with a UNION subquery:

(
            SELECT 10 AS id
  UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14
  -- etc.
) AS inline_table

You can do this from SQL Server 2008 onwards using a table value constructor.

SELECT * FROM (
   VALUES(1, 'red'),
         (2, 'orange'),
         (5, 'yellow'),
         (10, 'green'),
         (11, 'blue'),
         (12, 'indigo'),
         (20, 'violet'))
   AS Colors(Id, Value)

More information here: Table Value Constructor

CREATE TEMPORARY TABLE ids (id INT NOT NULL PRIMARY KEY);

INSERT
INTO    ids
VALUES
(10),
(11),
(12),
(13),
(14);

SELECT  *
FROM    ids
WHERE   id NOT IN
        (
        SELECT  id
        FROM    a
        );
create table B (id int)
insert into B values (10),(11),(12),(13),(14)

select *
from B
left join A 
on A.id=B.id
where A.id is null

drop table B

http://sqlfiddle.com/#!6/6666c1/30

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!