Home Forums Programming General column selection on dynamic basis RE: column selection on dynamic basis

  • Just use the same code I posted above except change it around to suit your needs.

    IF OBJECT_ID('tempdb..#TestTable') IS NOT NULL

    DROP TABLE #TestTable

    CREATE TABLE #TestTable (

    [ID] INT IDENTITY(1,1) NOT NULL,

    [Year] INT NULL,

    [Month] INT NULL,

    [FaultType1] VARCHAR(50) NULL,

    [FaultType2] VARCHAR(50) NULL,

    [FaultType3] VARCHAR(50) NULL,

    PRIMARY KEY (ID))

    INSERT INTO #TestTable

    SELECT 2011,11,'Mfg Defect','','' UNION ALL

    SELECT 2012,1,'','Power Overload','' UNION ALL

    SELECT 2012,3,'','','User Error' UNION ALL

    SELECT 2012,4,'Mfg Defect','','' UNION ALL

    SELECT 2012,4,'','','User Error' UNION ALL

    SELECT 2012,6,'','','User Error' UNION ALL

    SELECT 2013,1,'','Power Overload','' UNION ALL

    SELECT 2013,1,'Mfg Defect','','' UNION ALL

    SELECT 2013,2,'','Power Overload',''

    --SELECT * FROM #TestTable

    DECLARE

    @Response VARCHAR(50)

    ,@Year INT

    ,@strSQL VARCHAR(MAX)

    SET @Response = 'FaultType1'

    SET @Year = 2012

    --SET @Response = 'FaultType2'

    --SET @Year = 2011

    --SET @Response = 'FaultType3'

    --SET @Year = 2012

    SET @strSQL = '

    SELECT

    t.[ID]

    ,t.[Year]

    ,t.[Month]

    ,'+@Response+' AS '+@Response+'

    FROM

    #TestTable AS t

    WHERE

    NULLIF('+@Response+','''') IS NOT NULL

    AND Year >= '+CAST(@Year AS VARCHAR(5))+'

    ORDER BY

    Year, MONTH

    '

    EXEC(@strSQL)

    The point to take away from this is that to pass in metadata such as table or column names requires some dynamic sql somewhere. If this is going to occur a lot it MIGHT be beneficial to put the table and column mappings into a separate table then join on that. If you know the column names already and they are limited in number I think the dynamic sql approach is as good as any.