Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何在SQL Server中连接Select语句的列名_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql server 如何在SQL Server中连接Select语句的列名

Sql server 如何在SQL Server中连接Select语句的列名,sql-server,sql-server-2008,Sql Server,Sql Server 2008,现在,在你对这个问题发疯并开始批评这种思维方式之前,让我告诉你,我同意你的观点,这种完全非规范化的数据库设计让我和下一个人一样反感,但是,我们必须处理它,所以让我们开始吧 有一个数据库,有12列,一年中每个月一列(我知道,我知道…),当你计算那些列时,实际上是24列,说明什么进入和什么流出 它们被标记为Month1、Month2等,如您所料 我正试图找到一种方法来系统地选择一个基于a的专栏,等等,是的!月份值,因此1月份为1,等等 到目前为止,这还不起作用: SELECT Month+1 ...

现在,在你对这个问题发疯并开始批评这种思维方式之前,让我告诉你,我同意你的观点,这种完全非规范化的数据库设计让我和下一个人一样反感,但是,我们必须处理它,所以让我们开始吧

有一个数据库,有12列,一年中每个月一列(我知道,我知道…),当你计算那些列时,实际上是24列,说明什么进入和什么流出

它们被标记为Month1、Month2等,如您所料

我正试图找到一种方法来系统地选择一个基于a的专栏,等等,是的!月份值,因此1月份为1,等等

到目前为止,这还不起作用:

SELECT Month+1 ...
或者这个:

SELECT Month+@myMonth
所以,虽然我的第一个选择是建立一个好的数据库,但我没有办法,即使我有办法,我也不会被允许这样做


有没有办法解决这个问题?无需创建24个案例长的选择案例?

您可以创建一个单表值函数:

CREATE FUNCTION GetByMonth
(
    @month int
)
RETURNS TABLE
AS RETURN
(
    SELECT CASE @month
        WHEN 1 THEN Month1
        WHEN 2 THEN Month2
        --...
    END AS MonthData
    FROM Table1
)
您可以在以后选择,而无需始终写出案例:

SELECT MonthData
FROM GetByMonth(2) AS m
或者


一种方法是使用类似于so的unpivot:

declare @month int
set @month=11
select monthval
from (select * from months) p
unpivot 
(monthval for monthnum in
 (month1,month2,month3,month4,month5,month6,month7,month8,month9,month10,month11,month12)) u
where monthnum= 'month'+cast(@month as varchar(2))

SQLFiddle。

你说得通,我很吃惊,我最后不得不做这样的事情。我认为像这样简单的东西应该在SQLServer中实现。虽然我确信有非常充分的理由不这样做。您也可以使用动态SQL,但如果这样做,我建议您这样做,并且只使用动态SQL作为最后手段。使用动态SQL有问题吗?不是说我要去,我只是好奇。这本身就是个问题吗?不。但是a)它会使简单查询变得笨拙,b)如果做得不好,可能会导致SQL注入攻击,c)如果查询计划无法缓存,可能会导致性能下降,d)动态SQL无法与其他查询连接,e)在编写查询时带走intellisense。您似乎知道一些事情,所以我相信你的话。
declare @month int
set @month=11
select monthval
from (select * from months) p
unpivot 
(monthval for monthnum in
 (month1,month2,month3,month4,month5,month6,month7,month8,month9,month10,month11,month12)) u
where monthnum= 'month'+cast(@month as varchar(2))