获取带有值的SQL Server列名称

时间:2018-03-05 18:55:35

标签: sql sql-server sql-server-2016 information-schema

我正在尝试创建一个查询,允许我在其找到的列值旁边显示列名。

举个例子:

SELECT 
    * 
FROM 
    INFORMATION_SCHEMA.COLUMNS 
WHERE 
    TABLE_NAME = 'saverTbl'

以上内容将返回该表中的所有列名:

id, Link_userTblID, type, environment, vendor, theGUID, theGUID, etc etc...

现在我需要的是从值旁边的表名获取输出。这是我从表中获取值的查询:

SELECT 
    * 
FROM 
    saverTbl 
WHERE 
    LINK_userTblID = @val1

以上内容返回与LINK_userTblID匹配的行,如下所示:

32, 1, 'Blah', 'something', 'Adobe', 546656156-45332-54616516-4515, etc etc..

现在把它们放在一起(这就是这个问题的全部内容):

id: 32,
LINK_userTblID: 1,
type: Blah,
environment: something,
vendor: Adobe,
theGUID: 546656156-45332-54616516-4515,
etc etc.....

非常需要以json格式输出,但列名称匹配列值

2 个答案:

答案 0 :(得分:1)

假设这是一行,你可以试试这个:

WITH cte AS
(
    SELECT
    (SELECT TOP 1 * FROM sys.objects FOR XML PATH('row'),TYPE) AS TheXml
)
SELECT TheElement.value('local-name(.)','nvarchar(max)')
       + ': '
       + TheElement.value('text()[1]','nvarchar(max)') AS YourOutput
FROM cte
CROSS APPLY TheXml.nodes('/row/*') AS A(TheElement);

结果:

YourOutput
---------------
name: sysrscols
object_id: 3
schema_id: 4
parent_object_id: 0
type: S 
type_desc: SYSTEM_TABLE
create_date: 2012-02-10T20:15:58.693
modify_date: 2012-02-10T20:15:58.700
is_ms_shipped: 1
is_published: 0
is_schema_published: 0

XQueryXPath相关的XML是一个非常强大的工具集,可以解决相当普遍的问题。 cte构建一个如下所示的XML:

<row>
  <name>sysrscols</name>
  <object_id>3</object_id>
  <schema_id>4</schema_id>
  <parent_object_id>0</parent_object_id>
  <type>S </type>
  <type_desc>SYSTEM_TABLE</type_desc>
  <create_date>2012-02-10T20:15:58.693</create_date>
  <modify_date>2012-02-10T20:15:58.700</modify_date>
  <is_ms_shipped>1</is_ms_shipped>
  <is_published>0</is_published>
  <is_schema_published>0</is_schema_published>
</row>

/row/*的调用将<row>下的所有节点检索为派生表。其余的很容易XQuery

答案 1 :(得分:0)

试试这个:

SELECT * FROM saverTbl 
WHERE LINK_userTblID = @val1
FOR JSON PATH