How to make dynamic column name to the result?

  • Hi,

    I am using below command to get result but it always failed at "wrong character of '+'. It seems I can build column name with +. Do you have any ideas?

    select 'adfd' as 'cvr < ' + cast(18 as varchar(3))

    Thanks,

    coby

  • As far as I know, you cannot do this without resorting to dynamic sql.  Why do you want to do this?

  • select ('adfd'  + cast(18 as varchar(3))) as  'cvr < '

    Is this what you want?  The result is 'adfd18'

     

     

  • Thanks but I want the result to be

    cvr < 18

    ------------

    adfd

    I just want to make the column name to change by the value of the integer number, such as 18 above.

    Thanks,

    coby

  • Nothing changed.  You still have to use dynamic sql to do this.  But then again you shouldn't need dynamic sql.  So what do you need to do???

  • You cannot use "<" into a column name.

    CREATE TABLE [dbo].[tTest](

     [tcolumn] [varchar](20)

    ) ON [PRIMARY]

    GO

    insert into dbo.tTest (tcolumn) values ('adfd18')

    go

    declare @sqlString as nvarchar(100)

    declare @var as int

    set @var=18

    set @sqlString='select tcolumn as  cvrLessThan'+ltrim(cast(@var as varchar(3)))+' from dbo.tTest'

    exec sp_executesql @sqlString

    Good luck!

  • All,

    Thanks a lot for your suggestions.

    coby

  • That works for me!

    Select 'Demo' AS "Strange column < name"

  • Why are you trying to do this.

    you should do all this kind of stuff in the presentation layer.

    You cannot concatenate a string to give you a "Dynamic" Column name. (Unless you use dynamic sql as suggested)

     

Viewing 9 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic. Login to reply