我正在尝试检索有关我们环境中服务器的信息,并且我需要检索信息的某些服务器不存在。例如,ServerD,ServerF,ServerJ和ServerN不在我查询的表中。
SELECT Server, Active, Location
FROM Repository.dbo.Servers
WHERE Server IN (
'ServerA',
'ServerB',
'ServerC',
'ServerD',
'ServerE',
'ServerF',
'ServerG',
'ServerH',
'ServerI',
'ServerJ',
'ServerK',
'ServerL',
'ServerM',
'ServerN',
'ServerO'
)
ORDER BY ServerName
这些是此查询的结果,但我想要一些不存在的服务器(ServerD,ServerF,ServerJ和ServerN)的值,例如NULL等。
ServerA N Springfield, IL
ServerB Y Cleveland, OH
ServerC Y Springfield, IL
ServerE Y Cleveland, OH
ServerG Y Cleveland, OH
ServerH Y Memphis, TN
ServerI Y Springfield, IL
ServerK N Cleveland, OH
ServerL Y Cleveland, OH
ServerM Y Springfield, IL
ServerO Y Memphis, TN
如何在T-SQL中完成?例如,我希望返回类似于此的内容:
ServerA N Springfield, IL
ServerB Y Cleveland, OH
ServerC Y Springfield, IL
ServerD NULL
ServerE Y Cleveland, OH
ServerF NULL
ServerG Y Cleveland, OH
ServerH Y Memphis, TN
ServerI Y Springfield, IL
ServerJ NULL
ServerK N Cleveland, OH
ServerL Y Cleveland, OH
ServerM Y Springfield, IL
ServerN NULL
ServerO Y Memphis, TN
答案 0 :(得分:2)
Per your comments you have some table that does have all the servers. Use that table and left join the servers table.
SELECT t1.Server, t2.Active, t2.Location
FROM TheTableThatHasAllServers t1
LEFT JOIN Repository.dbo.Servers t2 on t1.server = t2.server
WHERE t1.Server IN (
'ServerA',
'ServerB',
'ServerC',
'ServerD',
'ServerE',
'ServerF',
'ServerG',
'ServerH',
'ServerI',
'ServerJ',
'ServerK',
'ServerL',
'ServerM',
'ServerN',
'ServerO'
)
ORDER BY t1.ServerName