Is there way to create a temporary table with just one column in t-sql, load it and retrieve data? Let me explain…
I have a sproc like this:
SELECT @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT '],[' + cast(MonthYear as varchar(10)) FROM vCountByMonthYear where
SiteGUID = @SiteGuid
and
MonthYear BETWEEN @StartDate AND @StopDate
ORDER BY '],[' + cast(MonthYear as varchar(10)) FOR XML PATH('') ), 1, 2, '') + ']'
SET @query = N'SELECT Wuc,LineCount, ' + @cols +' FROM (SELECT Wuc,MonthYear,LineCount,Value,OrderBy FROM vCountByMonthYear
where SiteGUID = ' + CHAR(39) + CONVERT(nvarchar(36), @SiteGuid) + CHAR(39) +
' and MonthYear BETWEEN '
+ CHAR(39)
+ CONVERT(nvarchar(10),@StartDate )
+ CHAR(39)
+ ' AND '
+ CHAR(39)
+ CONVERT(nvarchar(10),@StopDate )
+ CHAR(39)
+ ' ) p
PIVOT ( Sum ([Value] ) FOR MonthYear IN ( '+ @cols +' ) ) AS pvt ORDER BY Wuc,OrderBy'
execute(@query)
If I modify the view things get all messed up but I need to get additional info from that view – an EventId field. If add it to this query my results are all bad, so I thought I can create a temporaty table and insert what I need, then from a different sproc that would always run immediatelly afterwards would query the temp table and delete it.
Is that doable? How can you delete a table in the same sproc you just queried? I am I over thinking this?
Thanks,
Risho
You could create a global temp table (defined with ## instead of #). Since the exec runs in a different scope than the stored procedure you won’t be able to access a temp table defined in the scope of the stored procedure. You can then access that global temp table in your dynamic query and delete it at the end of the proc.
Everything will then have access to this global table, though, so be careful.