仅包括不为空的记录的属性

include only attributes of a record which are not null

亲爱的来自 Whosebug 的人们

我目前正在研究一种从数据库中导出数据的机制。每条记录大约有 30 个属性,我只想导出那些具有实际值的属性。

如果解释的不够准确,举个例子:

+----+-----------+------------+---------+--------+
| ID | Name      | Profession | Country | Salary |
+----+-----------+------------+---------+--------+
| 1  | John Doe  | NULL       | USA     | 5000   |
+----+-----------+------------+---------+--------+
| 2  | Jane Doe  | Painter    | NULL    | NULL   |
+----+-----------+------------+---------+--------+
| 3  | Jonas Doe | Butcher    | England | 8000   |
+----+-----------+------------+---------+--------+

Expected outputs:
John Doe: John Doe, USA, 5000
Jane Doe: Jane Doe, Painter
Jonas Doe: Jonas Doe, Butcher, England, 8000

这些输出应该在 XML 文件中生成。

如果可能的话,数据库中的每条记录都应该可以做到这一点。 我正在寻找一个函数来检查属性是否具有值,并根据该值将其添加到导出文件中。遗憾的是我找不到这样的东西。

编辑: 到目前为止我所做的只是编写查询以获取所有可能的属性:

CREATE PROCEDURE export @id int AS
BEGIN
SELECT Name,Profession,Country,Salary FROM Employee
WHERE ID = @id;
END
GO

您可以 select 您想要的 table 一切,使用 FOR XML PATH

WITH Employee (ID, [Name], Profession, Country, Salary) AS (
SELECT 1, 'John Doe', NULL, 'USA', 5000 UNION ALL
SELECT 2, 'Jane Doe', 'Painter', NULL, NULL UNION ALL
SELECT 3, 'Jonas Doe', 'Butcher', 'England', 8000
)

SELECT *
FROM Employee
FOR XML PATH

会return

<row>
  <ID>1</ID>
  <Name>John Doe</Name>
  <Country>USA</Country>
  <Salary>5000</Salary>
</row>
<row>
  <ID>2</ID>
  <Name>Jane Doe</Name>
  <Profession>Painter</Profession>
</row>
<row>
  <ID>3</ID>
  <Name>Jonas Doe</Name>
  <Profession>Butcher</Profession>
  <Country>England</Country>
  <Salary>8000</Salary>
</row>

编辑

WITH Employee (ID, [Name], Profession, Country, Salary) AS (
SELECT 1, 'John Doe', NULL, 'USA', 5000 UNION ALL
SELECT 2, 'Jane Doe', 'Painter', NULL, NULL UNION ALL
SELECT 3, 'Jonas Doe', 'Butcher', 'England', 8000
)

SELECT ID, (SELECT * FROM Employee S WHERE S.ID = M.ID FOR XML PATH) [XML]
FROM Employee M

return 每 ID 一行,它是 XML 数据。