Reputation: 5167
I have a table variable, called @t
, it is an instance of the specsAndModel type I defined here:
CREATE TYPE specsAndModel AS TABLE
(
specName VARCHAR(50)
,specVal VARCHAR(50)
)
Doing a select specName,specVal from @t
gives data of the form:
specName | specVal
--------------------------------
[modelNumber] | F00-B4R
[Internal Switch(es)] | 2.00000
[Number of Ports] | 1.00000
[Color Insulator] | Yellow
I inserted the first row so that when I transpose the table, there will be a modelNumber
field. I intend to join the transposed table to another on that field.
In order to account for a different number of records for different models, I constructed the pivot statement using string concatenation:
DECLARE @cols NVARCHAR(MAX);
DECLARE @query NVARCHAR(MAX);
SELECT @cols = COALESCE(@cols + ',' + specName, specName) FROM @t;
SET @query = N'SELECT ' + @cols
+ N' FROM @var src'
+ N' PIVOT (MAX(specVal) FOR specName in (' + @cols + N')) pvt;';
The query string looks like this:
SELECT [modelNumber],[Internal Switch(es)],[Number of Ports],[Color Insulator]
FROM @var src
PIVOT
(
MAX(specVal)
FOR specName in ([modelNumber],[Internal Switch(es)],[Number of Ports],[Color Insulator])
) pvt;
Finally, I use sp_executesql
to pass in the @t
variable, then execute the @query
string:
EXEC sp_executesql @query, N'@var specsAndModel readonly', @t
The result is this:
[modelNumber] | [Internal Switch(es)] | [Number of Ports] | [Color Insulator]
-----------------------------------------------------------------------------
NULL | NULL | NULL | NULL
I get the null values for all models, I constructed a toy example of this pivot here on sqlfiddle and it works as expected. I am not sure what I'm doing wrong.
How can I transpose this table without getting null values?
Upvotes: 0
Views: 974
Reputation: 247650
A couple of things to fix:
First, remove the [
from around your specName
values on your INSERT
statement.
Second, change the way you get your columns to this. This will add the [
around the specName
values:
DECLARE @cols NVARCHAR(MAX);
DECLARE @query NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(specName)
from @t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
If you do that, then your script will work:
DECLARE @cols NVARCHAR(MAX);
DECLARE @query NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(specName)
from @t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = N'SELECT ' + @cols
+ N' FROM @var src'
+ N' PIVOT (MAX(specVal) FOR specName in (' + @cols + N')) pvt;';
EXEC sp_executesql @query, N'@var specsAndModel readonly', @t
Upvotes: 5