如何将今天的月份与SQL Server视图中的列名进行比较

时间:2016-09-14 09:25:46

标签: sql sql-server-2008

我在ProjectDates表中有这样的列:

PDID (primary), ProjectID, D01072016, D02072016, D03072016 etc.

我想只选择当前月份与列名称匹配的那些列。

例如,D01072016(第07个月)与今天的当月不匹配,即09.因此,不应在视图中选择此列。

如何为这个条件制作一个select语句?

2 个答案:

答案 0 :(得分:3)

使用CASE

SELECT PDID,
   CASE MONTH(GETDATE())
   WHEN 1 THEN D01012016
   WHEN 2 THEN D01022016
   ...
   WHEN 12 THEN D01122016
   END AS D01CRT2016,
   CASE MONTH(GETDATE())
   WHEN 1 THEN D02012016
   WHEN 2 THEN D02022016
   ...
   WHEN 12 THEN D02122016
   END AS D02CRT2016,
FROM ...

根据需要重复每月的每一天,最多31个。祝你好运处理闰年。

答案 1 :(得分:1)

您可以从

获取列列表
declare @qry nvarchar(max)
set @qry = 'select '
select @qry = @qry + '[' + column_name +'],'
from information_schema.columns 
where table_name='ProjectDates ' and column_name like '%07%'  -- month
set @qry = left(@qry ,len(@qry )-1) 
set @qry = @qry + ' from ProjectDates '
exec sp_executesql @qry 

您需要构建一个动态查询,如...

    Config noSSL = Config.build().withEncryptionLevel(Config.EncryptionLevel.NONE).toConfig();

    Driver driver = GraphDatabase.driver("bolt://localhost",AuthTokens.basic("neo4j","root"),noSSL);
    Session session = driver.session();

    String query = "MATCH (n:test) RETURN n LIMIT 25";

    StatementResult result =session.run(query);

//  StatementResult result = session.run( "MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title" );
    while ( result.hasNext() )
    {
        Record record = result.next();
        System.out.println( record.get("author"));
      //  System.out.println( record.get( "title" ).asString() + " " + record.get("name").asString() );
    }

    session.close();
    driver.close();