具有案例功能的批量选择语句?

时间:2016-09-09 18:54:40

标签: sql sql-server

Select Site, IP from Router where site = '270'
Select Site, IP from Router where site = '271'
Select Site, IP from Router where site = '272'
Select Site, IP from Router where site = '273'
Select Site, IP from Router where site = '274'
...
.....
Select site, IP From Router where site = '300'

通常这会拉回四个输出行。然而,其中一些记录并不存在。我一直在通过批量更新语句在这些站点上运行IP更新。无论如何,如果网站不存在,还是要向此添加一个case语句以返回吗?

例如:

select site,IP from router 
Case = Site 
When site = '270' then site,IP
when site = '270' then site,IP
else 'Null'
end
where site in (270,271,...ect.)

2 个答案:

答案 0 :(得分:0)

您可以这样使用CASE

select 
    case site 
         When site in (270,271,...ect.) then site else 'NULL' end as site, 
    case site 
         When site in (270,271,...ect.) then ip  else 'NULL' end  as ip
from my_table    
where site in (270,271,...ect.)

答案 1 :(得分:0)

对于没有记录的网站,

WHERE site IN ()不会返回任何内容,您可以做的是从包含您要包含的网站列表的驱动程序表中使用左连接到router表,您可以从这样的值列表中查询:

SELECT a.site,b.IP
FROM (VALUES (270), (271), (272), (273), (274), (275), (276)) AS a(sites)
LEFT JOIN router b
  ON a.sites = b.site
ORDER BY a.site,b.IP

或者,如果您要在表格中查询site值列表:

SELECT a.site,b.IP
FROM sitelist a
LEFT JOIN router b
  ON a.site = b.site
ORDER BY a.site,b.IP

除了存在的所有site / site组合之外,这将为列表/表格中的每个ip至少返回一条记录。