Dynamic Pivot Query without storing query as String

筅森魡賤 提交于 2019-12-23 21:32:09

问题


I am fully familiar with the following method in the link for performing a dynamic pivot query. Is there an alternative method to perform a dynamic pivot without storing the Query as a String and inserting a column string inside it?

http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx


回答1:


Short answer: no.

Long answer:

Well, that's still no. But I will try to explain why. As of today, when you run the query, the DB engine demands to be aware of the result set structure (number of columns, column names, data types, etc) that the query will return. Therefore, you have to define the structure of the result set when you ask data from DB. Think about it: have you ever ran a query where you would not know the result set structure beforehand?

That also applies even when you do select *, which is just a sugar syntax. At the end, the returning structure is "all columns in such table(s)".

By assembling a string, you dynamically generate the structure that you desire, before asking for the result set. That's why it works.

Finally, you should be aware that assembling the string dynamically can theoretically and potentially (although not probable) get you a result set with infinite columns. Of course, that's not possible and it will fail, but I'm sure you understood the implications.

Update

I found this, which reinforces the reasons why it does not work.

Here:

SSIS relies on knowing the metadata of the dataflow in advance and a dynamic pivot (which is what you are after) is not compatible with that.

I'll keep looking and adding here.



来源:https://stackoverflow.com/questions/6831364/dynamic-pivot-query-without-storing-query-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!