I have a procedure that uses the dynamic input parameter @Instring VarChar = '1,2,3,4'
. This procedure populates @RetTable
like this:
myDates myReturns ID
2012-05-02 0.020 1
2012-05-03 -0.017 1
2012-05-04 -0.026 1
2012-05-02 0.009 2
2012-05-03 0.004 2
2012-05-04 -0.003 2
2012-05-02 -0.003 3
2012-05-03 -0.005 3
2012-05-04 -0.003 3
2012-05-02 0.004 4
2012-05-03 0.010 4
2012-05-04 -0.021 4
I then want to pivot or transpose @RetTable
by the ID
column to look like this:
myDates 1 2 3 4
2012-05-02 0.020 0.009 -0.003 0.004
2012-05-03 -0.017 0.004 -0.005 0.010
2012-05-04 -0.026 -0.003 -0.003 -0.021
this is the code I have thus far:
Select * From @ReturnsTable
Pivot(Max(myReturns) For [ID] In ([1],[2],[3],[4])) As myPTable
This part of code:
([1],[2],[3],[4]))
I want to replace with/to reference @InString
in order to have a dynamic procedure. I have tried various dynamic sql posts on SO but run into issues with every other attempt. Any ideas?
EDIT:
In answer to @bluefeet. What I have tried;
1)
Execute
('Select * From @TempTable
Pivot(Max(myReturns) For ID In (' + @InString + ')) As myPTable')
Result: error must declare @TempTable - table out of scope
2) Then changed @TempTable
to #TempTable
;
Prints as:
Select * From #TempTable
Pivot(Max(myReturns) For ID In (1,2,3)) As myPTable
When execute that, I get error: Incorrect syntax near '1'
Which leads me to think the ID
's should be delimited as [1],[2],[3]
..
Earlier I have also tried executing with the normal execute
, but also the Exec sp_executesql