josephpmo
asked on
sql unpivot with dynamic column names and data values
I am trying to extract the column names and field value for that column for a given user for a table that can be dynamic in length
Password EmployeeNo AdminProgram SaleExpenseCodes Company Branch Department Personnel Security Nextfield Nextfield1 Nextfield2 etc...
barry22 98315 0 -1 0 0 0 -1 -1
blanke4 98166 0 -1 -1 -1 -1 -1 -1
bogart1 98284 0 -1 -1 -1 -1 -1 -1
Desired Result for employee 98315
FieldName FieldValue
AdminProgram 0
SaleExpenseCodes -1
Company 0
Branch 0
Department 0
Personnel -1
Security -1
I have figured out how to extract the column names to a variable as follows
but I am having trouble folding that into the UNPIVOT statement. Can anyone point me in the right direction.
Password EmployeeNo AdminProgram SaleExpenseCodes Company Branch Department Personnel Security Nextfield Nextfield1 Nextfield2 etc...
barry22 98315 0 -1 0 0 0 -1 -1
blanke4 98166 0 -1 -1 -1 -1 -1 -1
bogart1 98284 0 -1 -1 -1 -1 -1 -1
Desired Result for employee 98315
FieldName FieldValue
AdminProgram 0
SaleExpenseCodes -1
Company 0
Branch 0
Department 0
Personnel -1
Security -1
I have figured out how to extract the column names to a variable as follows
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.name)
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('dbo.Secure')
and c.name<>'employeeno'
for xml path('')), 1, 1, '')
but I am having trouble folding that into the UNPIVOT statement. Can anyone point me in the right direction.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER