如何基于变量重命名列

时间:2011-11-02 14:39:22

标签: sql-server tsql rename

我想基于变量在一系列查询的末尾重命名列。它会执行类似这样的事情:

 DECLARE @formTable TABLE (FormID varchar(max))
    INSERT @formTable SELECT 'Form1'AS FormID;
    INSERT @formTable SELECT 'Form2'AS FormID;
    INSERT @formTable SELECT 'Form3' AS FormID;
    INSERT @formTable SELECT 'Form5'     AS FormID;


 DECLARE @CCount TABLE (FormID varchar(max), Present varchar(max))
    INSERT @CCount SELECT 'Form1' AS FormID, 'Yes' AS Present;
    INSERT @CCount SELECT 'Form2' AS FormID, 'Yes' AS Present;

 DECLARE @subject varchar(12);
 SET @subject = 'Subject 22'

 SELECT t.FormID AS Form, Present  
 FROM  @formTable t LEFT JOIN @CCount c ON t.FormID = c.FormID

创建一个如下所示的表:

 Form     Present
 Form1      Yes
 Form2      Yes
 Form3      NULL
 Form5      NULL

我希望它看起来像这样:

  Form     Subject 22
  Form1      Yes
  Form2      Yes
  Form3      NULL
  Form5      NULL

我该如何做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:1)

您不能将变量用于列名称 - 您可以使用dynamic SQL执行此操作,但您需要非常小心动态SQL而不要引入SQL injection vulnerability

答案 1 :(得分:0)

一种方法是动态SQL:

declare @sql nvarchar(max)
set @sql = 'SELECT t.FormID AS Form, Present as [' + @subject + 
    '] FROM  @formTable t LEFT JOIN @CCount c ON t.FormID = c.FormID'
exec @sql