如何将列名显示为另一列中的数据

时间:2014-02-08 07:03:16

标签: sql sql-server-2008 exec

我有这样的查询。

EXEC('SELECT FirstName, LastName,' + @Subject + ' FROM Student')

我必须再显示一列,它是动态选择的列名称“Subject”的前2个字母。 我尝试过如下使用SUBSTRING函数,但是它获取数据的前2个字母。相反,我想获取列名的前2个字母。请告诉我这里我做错了什么。

EXEC('SELECT FirstName, LastName,' + @Subject + ', SUBSTRING('+@Subject+',1,2)  FROM Student') 

2 个答案:

答案 0 :(得分:3)

您可以将子字符串移到外面:

假设该列实际存在于表中:

DECLARE @SUBJECT_SPLIT VARCHAR(10)
SET @SUBJECT_SPLIT = SUBSTRING(@subject,1,2)
EXEC('SELECT FirstName, LastName,' + @Subject + ',' + @SUBJECT_SPLIT + ' FROM Student')

假设该列不会出现在物理上:

DECLARE @SUBJECT_SPLIT VARCHAR(10)
SET @SUBJECT_SPLIT = SUBSTRING(@subject,1,2)
EXEC('SELECT FirstName, LastName,' + @Subject + ', '' AS ' + @SUBJECT_SPLIT + ' FROM Student')

答案 1 :(得分:0)

DECLARE @SUBJECT_SPLIT VARCHAR(10)
SET @SUBJECT_SPLIT = SUBSTRING(@subject,1,2)
EXEC('SELECT FirstName, LastName,' + @Subject + ', ''' + @SUBJECT_SPLIT + '''
FROM Student')

我使用+ @ SUBJECT_SPLIT +周围的3个引号来给出正确的值。我不知道它为什么会使用3个引号,如果有人可以的话会有很大的帮助。