locked
Select data where column name is current month name RRS feed

  • Question

  • User-809753952 posted

    I have a table in which column names are month names.

    I want to select data only for the column name which has current month name.

    SELECT  [Aug] FROM table where [colum name = current month] ( As August is the current month)

    Wednesday, August 1, 2018 8:37 AM

Answers

  • User-2146987983 posted

    Follow along the sample:

    DECLARE @sql VARCHAR(2000)
    
    CREATE TABLE TAB(
    	[JAN] INT,
    	[FEB] INT,
    	[MAR] INT,
    	[APR] INT,
    	[MAY] INT,
    	[JUN] INT,
    	[JUL] INT,
    	[AUG] INT,
    	[SEP] INT,
    	[OCT] INT,
    	[NOV] INT,
    	[DEC] INT
    )
    
    INSERT INTO TAB 
    SELECT 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
    
    SELECT * FROM TAB
    
    SET @sql = 'SELECT ' + FORMAT(GETDATE(), 'MMM', 'en-US')  + ' FROM TAB'
    
    EXEC(@sql)
    
    DROP TABLE TAB

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 1, 2018 9:05 AM
  • User-809753952 posted

    Hi me_ritz ! Thanks for your answer. Format function is not working in my sql server edition. Instead I used  Datename(MONTH, GETDATE()) .

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 1, 2018 9:18 AM

All replies

  • User-2146987983 posted

    Follow along the sample:

    DECLARE @sql VARCHAR(2000)
    
    CREATE TABLE TAB(
    	[JAN] INT,
    	[FEB] INT,
    	[MAR] INT,
    	[APR] INT,
    	[MAY] INT,
    	[JUN] INT,
    	[JUL] INT,
    	[AUG] INT,
    	[SEP] INT,
    	[OCT] INT,
    	[NOV] INT,
    	[DEC] INT
    )
    
    INSERT INTO TAB 
    SELECT 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
    
    SELECT * FROM TAB
    
    SET @sql = 'SELECT ' + FORMAT(GETDATE(), 'MMM', 'en-US')  + ' FROM TAB'
    
    EXEC(@sql)
    
    DROP TABLE TAB

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 1, 2018 9:05 AM
  • User-809753952 posted

    Hi me_ritz ! Thanks for your answer. Format function is not working in my sql server edition. Instead I used  Datename(MONTH, GETDATE()) .

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 1, 2018 9:18 AM