Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 dynamic query issue

Author  Topic 

Vishal_sql
Posting Yak Master

102 Posts

Posted - 2013-06-21 : 03:55:14

How can i get the #TotalYears table for further use in same schema

below code doesnot allow me see the select * from #TotalYears

can anyone let me know what is issue in the script

DECLARE @TabColumns NVARCHAR(MAX)=''
DECLARE @RecCntr INT = 1
DECLARE @TotalYrs INT = 5

WHILE (@RecCntr <= @TotalYrs)
BEGIN
SET @TabColumns = @TabColumns+'Year'+ CONVERT(VARCHAR(10),@RecCntr)+' '+'REAL'+','
SET @RecCntr = @RecCntr + 1
END

DECLARE @SQLStr NVARCHAR(MAX)

IF OBJECT_ID(N'tempdb..#TotalYears', N'U') IS NOT NULL
BEGIN
DROP TABLE #TotalYears;
END

SET @SQLStr = N'CREATE TABLE #TotalYears '+' '+'(Solution VARCHAR(200),'+ @TabColumns +')'


SET @SQLStr = LEFT(@SQLStr,LEN(@SQLStr)-2) +')'
SELECT @SQLStr
EXECUTE SP_EXECUTESQL @SQLStr


select * from #TotalYears

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-06-21 : 04:00:15
the problem is because temporary table is created inside dynamic sql. Why cant you create it outside in static way? where are you getting columnnames from?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -