SQL view with dynamic count of columns

后端 未结 2 1629
悲&欢浪女
悲&欢浪女 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)
    
    0 讨论(0)
  • 2021-01-24 04:04

    This is not possible in standard SQL, nor in any version of SQL that I am familiar with (SQL Server, Oracle, MySql, Access SQL). Tables, Expressions and Views in SQL have a fixed column-set, by design. I.E., it's intentionally restricted this way. AFAIK, in most versions of SQL, Stored Procedures are the only objects that can return a variable column-set.

    0 讨论(0)
提交回复
热议问题