使用函数或视图将数据从行转换为列

时间:2016-01-21 15:50:39

标签: sql sql-server sql-server-2008-r2 sql-view sql-function

我需要在视图或函数中将数据从行转换为列,我读到了 这句话:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
 @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ' + @cols + ' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + ')
            ) p '

execute(@query)

但我希望它在视野中或功能上,  我尝试在Function中创建它:

CREATE FUNCTION fn_eForm_Control_Instance
(@EFormID INT)

RETURNS TABLE
AS
    DECLARE 
    @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(FieldName) 
                    from vwE_Form_Control_Instance
                    where EFormID = @EFormID
                    group by FieldName, SortID,EFormID
                    order by SortID
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT EFormID, EForm_InstanceID
, ' + @cols + '  from 
             (
                select FieldInstance, FieldName, EForm_InstanceID, EFormID
                from vwE_Form_Control_Instance
                where EFormID = @EFormID
            ) x
            pivot 
            (
                max(FieldInstance)
                for FieldName in (' + @cols + ')
            ) p '

    RETURN

但它给了我错误信息"键盘附近的语法错误' DECLARE' "

*我正在使用sql server 2008 r2

2 个答案:

答案 0 :(得分:0)

如果后面的内容是单个SQL语句,则只能创建compile project(':RCTVideo') 的函数。这称为内联表值函数。查看documentation

如果您有一个动态SQL查询,那么您将无法使用函数或视图执行此操作。您唯一的选择是使用存储过程。

答案 1 :(得分:0)

语法错误的原因是RETURNS TABLE必须后跟表定义:

RETURNS TABLE (
Col1 int, 
Col2 varchar(31),
etc...
)

DECLARE ...

然而,TT的答案也包含有效点。