February 13, 2014 at 9:01 am
Example: Run a query that finds the following:
User 1 has 5 quiz results
User 2 has 3 quiz results
User 3 has 1 quiz result
User 4 has 9 quiz results
I want to dynamically create a temp table 2ith 9 columns that I can use for lookups a later time. Is there a way to achieve this?
Many thanks for any suggestions!
February 13, 2014 at 9:05 am
Yes you can with dynamic code. But you might face the same issues when calling that table. Why wouldn't you want to use a normalized temp table?
February 13, 2014 at 9:08 am
I would consider a static temp table and if you wish, look at creating a dynamic pivot query.
February 13, 2014 at 9:13 am
Because my values can change each time I run it. Today there might be 9 quiz results, but tomorrow there might be 12. Just want to be able to dynamically built a table with 9 columns that I can use in my searches.
February 13, 2014 at 9:15 am
I've never used a dynamic pivot. Can you give an example?
February 13, 2014 at 9:18 am
To do a dynamic pivot, check the following article: http://www.sqlservercentral.com/articles/Crosstab/65048/
If you build your table something like this, it doesn't matter if you have 1, 3 or 200 results:
CREATE TABLE Quiz_Results(
quiz_id int,
result_no int,
result_value varchar(50) --int, decimal or whatever you need
)
February 13, 2014 at 9:36 am
If you did want to do it (and I agree that the normalised solution is better) you'd need to go with a Global Temp table rather than just a normal one.
For example, in this code:
DECLARE @sSQL NVARCHAR(MAX);
SET @sSQL =
'
CREATE TABLE #tmp (
Col1 INT,
Col2 INT);
INSERT INTO #tmp VALUES (1,21),(2,23),(3,35);
SELECT * FROM #tmp
'
EXEC sp_executesql @sSQL
SELECT * FROM #tmp
the select within the dynamic SQL works but the one outside doesn't. This is because the temp table is scoped within the dynamic code and not visible to anything else.
However, if you use a global temp:
DECLARE @sSQL NVARCHAR(MAX);
SET @sSQL =
'
CREATE TABLE ##tmp (
Col1 INT,
Col2 INT);
INSERT INTO ##tmp VALUES (1,21),(2,23),(3,35);
SELECT * FROM ##tmp
'
EXEC sp_executesql @sSQL
SELECT * FROM ##tmp
then both selects work fine.
February 13, 2014 at 11:33 am
Richard Warr (2/13/2014)
If you did want to do it (and I agree that the normalised solution is better) you'd need to go with a Global Temp table rather than just a normal one.
The problem with Global Temp Tables is they destroy the ability to run concurrent code.
You don't need a Global Temp Table for this. You can create a Temp Table with just the "backbone" columns and add columns to it on the fly.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply