如何在SQL中获得12个月的列名 [英] How do I get 12 months as column names in SQL

查看:305
本文介绍了如何在SQL中获得12个月的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将月份和年份作为参数传递给查询。

我需要基于月份和年份的最后12个月份。



例如:

我将2016年1月作为参数。

我想得到列名为



 1月15日,2月15日,3月15日,4月15日,,,,,,,,,,, 12月15日

解决方案

如解决方案1中所述,这可以通过不同方式完成。但是,如果可能的话,我会避免使用动态列名。在使用结果集时,经常使用动态名称会引入其他问题和复杂性。根据情况,列的顺序可能会改变,或者主叫方不知道格式化的名称等等。



如果可能的话,我会提供数据到调用端(单独的查询,结果集中的标题行等)并使用固定的列名称,并根据每列的已知名称在客户端进行可能的重命名。

有两种方法。使用 PIVOT 命令或使用动态SQL和 sp_ExecuteSQL



如果你使用动态SQL,请确保将所有参数作为参数传递给它,以消除SQL注入漏洞。



有人已回答几乎这个问题这里的动态SQL方法:



如何在SELECT语句中获取动态列名 [ ^ ]



如需使用 PIVOT 请参阅以下内容:



sql - PIVOT with MONTH() - Stack Overflow [ ^ ]

I am passing Month and Year as Parameters to the Query.
I need Last twelve trailing months based on month and year.

For Eg:
I am giving January , 2016 as parameter.
I want to get the column names as

Jan-15,Feb-15,Mar-15,Apr-15,,,,,,,,,,,Dec-15

解决方案

As said in solution 1 this can be done in different ways. However, if possible I would avoid using dynamic column names. Very often using dynamic names introduces other problems and complexity when the result set is used. Depending on the situation the order of the columns may change or the calling side is unaware of the formatted names and so on.

So if possible, I'd provide the data to the calling side (a separate query, a header row in the result set etc.) and use fixed column names and do the possible renaming on the client side based on the known names for each column.


There are two ways. Using the PIVOT command or using dynamic SQL and sp_ExecuteSQL.

If you use dynamic SQL make sure you pass all your parameters into it's execution as parameters to negate SQL injection vulnerabilities.

Someone has answered almost this exact question using the dynamic SQL method here:

How to get Dynamic Column names in SELECT statement[^]

For help using the PIVOT see the following:

sql - PIVOT with MONTH() - Stack Overflow[^]


这篇关于如何在SQL中获得12个月的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆