仅包含记录的属性,这些属性不为null

时间:2018-08-24 09:37:12

标签: sql-server tsql sqlbulkcopy

亲爱的人们,来自stackoverflow

我目前正在研究一种从数据库导出数据的机制。每条记录大约都有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

1 个答案:

答案 0 :(得分:1)

您可以使用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

会返回

<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

ID将返回一行XML数据。