您可以像这样阅读信息:
- 首先创建一个包含所有
<environment>
节点的CTE
SELECT
在带有普通WHERE
子句的简单子句中使用派生表
试试这样:
DECLARE @xml XML='<environments>
<environment>
<name>DEV3WEB</name>
<databaseservername>DEV3DB.apc.com</databaseservername>
<webservername>DEV3WEB.abc.com/</webservername>
<appservername>DEV3APP.abc.com</appservername>
</environment>
<environment>
<name>DEV3APP</name>
<databaseservername>DEV3DB.abc.com</databaseservername>
<webservername>DEV3WEB.abc.com/</webservername>
<appservername>DEV3APP.abc.com</appservername>
</environment>
</environments>';
DECLARE @MachineName NVARCHAR(MAX)=N'DEV3APP';
WITH AllEnvironments AS
(
select env.value('name[1]','nvarchar(max)') AS Environment_Name
,env.value('databaseservername[1]','nvarchar(max)') AS Environment_DatabaseServername
,env.value('webservername[1]','nvarchar(max)') AS Environment_WebServername
,env.value('appservername[1]','nvarchar(max)') AS Environment_AppServername
FROM @xml.nodes(N'environments/environment') AS A(env)
)
SELECT *
FROM AllEnvironments
WHERE Environment_Name=@MachineName;
使用更大的 XML 设置过滤器以减少那里的工作量会更快XQuery
(查看.nodes()
-function):
DECLARE @MachineName NVARCHAR(MAX)=N'DEV3APP';
SELECT env.value('name[1]','nvarchar(max)') AS Environment_Name
,env.value('databaseservername[1]','nvarchar(max)') AS Environment_DatabaseServername
,env.value('webservername[1]','nvarchar(max)') AS Environment_WebServername
,env.value('appservername[1]','nvarchar(max)') AS Environment_AppServername
FROM @xml.nodes(N'environments/environment[name=sql:variable("@MachineName")]') AS A(env)