1

Is there any way to give conditional alias to SQL columns?.

Because I have two tables for Fields and Category. Meaning of each field changes conditionally.

 DECLARE @f1 NVARCHAR(10);
 set @f1= (select Field1 from Category);
 select Field1 as @f1 from AdditionalFields 
2
1

You should use a dynamic query.

 DECLARE @f1 NVARCHAR(10);
 set @f1= 'MyCategory'

 DECLARE @CMD NVARCHAR(MAX);
 SET @CMD = 'SELECT Field1 AS ' + @f1 + ' FROM MyTable';

 SELECT @CMD;
  --EXEC (@CMD);
GO
| (No column name)                         |
| :--------------------------------------- |
| SELECT Field1 AS MyCategory FROM MyTable |

dbfiddle here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.