You must Sign In to post a response.
  • Category: SQL Server

    How dynamically update the column name in SQL inside the case statement.

    How dynamically update the column name in SQL inside the case statement.

    DECLARE @CNT INT=1
    DECLARE @COL VARCHAR(15)='RM_TGT' + CONVERT(VARCHAR,@CNT)
    DECLARE @Heading VARCHAR(25)=NULL
    WHILE @CNT<=12
    BEGIN
    IF (@CNT=1 )
    SET @Heading='TARGETS(S): '
    ELSE
    SET @Heading=''
    UPDATE [DenaliConversion].[dbo].[RM_CAFILE_MO_FACTORS_NEW]
    SET CUSTOM_TEXT_01 =CUSTOM_TEXT_01 + CHAR(10) + @Heading +
    CASE
    WHEN @COL='01' THEN 'ANIMALS/LIVESTOCK' + ', '
    WHEN @COL='02' THEN 'AUTO PARTS' + ', '
    WHEN @COL='03' THEN 'CASH/NOTES' + ', '
    WHEN @COL='04' THEN 'CLASSROOM EQUIPMENT' + ', '
    WHEN @COL='05' THEN 'CLOTHING/FURS' + ', '
    ELSE
    @COL + ', '
    END
    SET @CNT=@CNT + 1
    END;
  • #763691
    Hi Abey,

    can you please explain your needs correctly.
    I think you want to be change the column name dynamically means you can try using alter query ..

    Ex:
    DECLARE @CNT INT
    DECLARE @COL VARCHAR(15)
    DECLARE @Heading VARCHAR(25)
    set @cnt=1
    set @COL='RM_TGT' + CONVERT(VARCHAR,@CNT)
    set @Heading =null
    select @cnt,@COL,@Heading
    WHILE @CNT<=12
    BEGIN
    IF (@CNT=1 )
    SET @Heading='TARGETS(S): '
    ELSE
    SET @Heading= ALTER TABLE table_name RENAME
    COLUMN old_name to
    CASE
    WHEN @COL='01' THEN 'ANIMALS/LIVESTOCK' + ', '
    WHEN @COL='02' THEN 'AUTO PARTS' + ', '
    WHEN @COL='03' THEN 'CASH/NOTES' + ', '
    WHEN @COL='04' THEN 'CLASSROOM EQUIPMENT' + ', '
    WHEN @COL='05' THEN 'CLOTHING/FURS' + ', '
    ELSE
    @COL + ', '
    ENd

    SET @CNT=@CNT + 1
    end


Sign In to post your comments