SQL view with dynamic count of columns

后端 未结 2 1630
悲&欢浪女
悲&欢浪女 2021-01-24 03:45

I know it is impossible directly, but maybe with help of sql functions it is possible to create view with dynamic column count? What exactly I want to do is - Create view which\

2条回答
  •  盖世英雄少女心
    2021-01-24 04:01

    I've made some assumptions about your data schema but it looks like you're trying to generate something like this

    CREATE VIEW User_Properties AS
    SELECT 
    [username], [date]
    ,MAX(CASE WHEN [PropertyName] = 'property 1' THEN [PropertyValue]  ELSE NULL END) AS [property 1]
    ,MAX(CASE WHEN [PropertyName] = 'property 2' THEN [PropertyValue]  ELSE NULL END) AS [property 2]
    ,MAX(CASE WHEN [PropertyName] = 'property 3' THEN [PropertyValue]  ELSE NULL END) AS [property 3]
    ....
    ,MAX(CASE WHEN [PropertyName] = 'property n' THEN [PropertyValue]  ELSE NULL END) AS [property n]
    GROUP BY [username], [date]
    

    Which can be automated along the lines of

    --Cursor to return the list of Properties
    DECLARE PROPERTY_CURSOR CURSOR FOR SELECT PropertyName From UserPropertyTable
    
    DECLARE @PropertyName nvarchar(255)
    DECLARE @SQL nvarchar(max)
    
    --Start Building the view definition
    SET @SQL ='CREATE VIEW User_Properties AS
    SELECT [username], [date]'
    
    --Add a column for each Property
    OPEN PROPERTY_CURSOR 
    FETCH NEXT FROM PROPERTY_CURSOR INTO @PropertyName
    WHILE @@FETCH_STATUS =0
    BEGIN
    SET @SQL = ',MAX(CASE WHEN [PropertyName] = '+QUOTENAME(@PropertyName,'''')+' THEN [PropertyValue]  ELSE NULL END) AS '+QUOTENAME(@PropertyName)
    FETCH NEXT FROM PROPERTY_CURSOR INTO @PropertyName
    END
    DEALLOCATE PROPERTY_CURSOR 
    
    
    --Finish off the Create_View SQL 
    SET @SQL =@SQL +'
    FROM UserPropertyTable
    GROUP BY [username], [date]'
    
    --Execute the Create_View SQL 
    EXEC (@SQL)
    

提交回复
热议问题