1

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's columns would be username (first table's values), date (second table's values), and multiple columns for properties (each third table's row would be column).User table structure - ID and username, Date table structure - ID and datetime, Property table structure - ID, property name, property value, fk user ID (plus one table to relate tables). Result should look something like that (columns):

|username| date | property 1|....|property n|

Can anyone could show any simple sample ?

Vilius
  • 786
  • 1
  • 6
  • 14

2 Answers2

2

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.

RBarryYoung
  • 55,398
  • 14
  • 96
  • 137
0

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)
Tom Page
  • 1,211
  • 1
  • 7
  • 8