I am using the exec(“query_string”) command on sql server. The matter is that the changes executed by this command cannot seen outside.
I mean that, I try to create a temp table with dynamic columns in a exec command an it runs ok, but when I try to make a select statement over created table I receive a error message that says that the table does not exists.
I know that is a context problem and my cuestion is how I make to exec command runs on a same context just like other sql statements???
CREATE TABLE #Test ( TheDate datetime, Harvest int )
INSERT INTO #Test(TheDate, Harvest) VALUES ('2011/10/11', 50)
INSERT INTO #Test(TheDate, Harvest) VALUES ('2012/10/11', 100)
INSERT INTO #Test(TheDate, Harvest) VALUES ('2011/10/01', 20)
INSERT INTO #Test(TheDate, Harvest) VALUES ('2011/12/11', 50)
INSERT INTO #Test(TheDate, Harvest) VALUES ('2011/11/11', 50)
INSERT INTO #Test(TheDate, Harvest) VALUES ('2011/11/12', 150)
DECLARE @listCol2 varchar(max)
SET @listCol2 =
(SELECT DISTINCT ('[' + CONVERT(varchar,YEAR(TheDate)) + '-' + RIGHT('0'+CONVERT(varchar,MONTH(TheDate)),2) +'] date,')
FROM #Test
ORDER BY ('[' + CONVERT(varchar,YEAR(TheDate)) + '-' + RIGHT('0'+CONVERT(varchar,MONTH(TheDate)),2) +'] date,') ASC
FOR XML PATH(''))
SET @listCol2 = LEFT(@listCol2,LEN(@listCol2)-1)
SELECT @listCol2
EXEC ('CREATE TABLE #Test2 ('+@listCol2+')')
SELECT * FROM #Test2 --In this line I got this message: the name of the object #Test2 isn't valid, why???
DROP TABLE #Test2
DROP TABLE #Test
Thanks
you can have following options.