简体   繁体   English

获取地图 <Column,ValueOfTheColumn> 从SQL查询(C#MVC5)

[英]get map<Column,ValueOfTheColumn> from a sql query (C# MVC5)

I have a C# method that returns perfectly a sql string query (unknown columns + unknown table + unknown conditions). 我有一个C#方法,可以完美地返回sql字符串查询(未知列+未知表+未知条件)。

How can I get a map as a result of executing the query ? 执行查询后如何获取地图?

Thank you. 谢谢。

Edit 编辑

(copied from an OP's answer, which should not have been an answer by Shnugo) (摘自OP的回答,Shnugo不应回答)

Guys sorry if that is not clear enough, I mean having as a result : KeyValuePair<string, string> 伙计们抱歉,如果这还不够清楚,我的意思是因为: KeyValuePair<string, string>

  • the first string is the column name or the alias, 第一个字符串是列名或别名,
  • the second string is the value returned from the query 第二个字符串是查询返回的值

I don't know what is the table, the columns on SQL, it's a method that generate the query, I'm trying to build something dynamic. 我不知道什么是表,SQL上的列,这是一种生成查询的方法,我正在尝试构建动态的东西。

I hope that's more clear. 我希望这更加清楚。

With SQL Server you have two approaches 使用SQL Server,您有两种方法

Try this 尝试这个

EXEC sp_describe_first_result_set N'SELECT * FROM sys.objects'; 

or 要么

SELECT  TOP 0 * FROM sys.objects FOR XML RAW,XMLSCHEMA

or 要么

SELECT  TOP 0 * FROM sys.objects FOR XML RAW,XMLDATA

UPDATE UPDATE

Your edit told me, that you are trying to create a list of Key-Value-Pairs out of an unknown table / query result. 您的编辑告诉我,您正在尝试从未知表/查询结果中创建键值对列表。

One approach is to create an XML result and use the XMLs great abilities to deal with generic structures: 一种方法是创建XML结果,并使用XML的强大功能来处理通用结构:

In this case the unknown query is SELECT * FROM sys.objects . 在这种情况下,未知查询为SELECT * FROM sys.objects To be able to know, to which row a KVP belongs, there must be a RowKey : 为了知道KVP属于哪一行,必须有一个RowKey

SELECT r.value('@RowKey','nvarchar(max)') AS RowKey
      ,attr.value('local-name(.)','nvarchar(max)') AS ColumnName
      ,attr.value('.','nvarchar(max)') AS ColumnValue
FROM
(
SELECT 
    (
    SELECT o.object_id AS RowKey
           ,* 
    FROM sys.objects AS o 
    FOR XML RAW,TYPE
    ) 
) AS TableRows(InXML)
CROSS APPLY TableRows.InXML.nodes('/row') AS A(r)
CROSS APPLY A.r.nodes('@*') AS B(attr)

The (partial) result (部分)结果

Key ColumnName          ColumnValue
3   RowKey              3
3   name                sysrscols
3   object_id           3
3   schema_id           4
3   parent_object_id    0
3   type                S 
3   type_desc           SYSTEM_TABLE
[many more]

Warning 警告

Whatever you are trying to achieve: KVP -solutions tend to become a severe headache... (type safety, castings, pivoting...) 无论你正在努力实现:KVP -solutions往往成为一个严重的头痛...(类型安全,铸件,旋转...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM