﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2008 / SQL Server 2008 - General  / EXEC sql string that has table variable / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Mon, 20 May 2013 10:48:49 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: EXEC sql string that has table variable</title><link>http://www.sqlservercentral.com/Forums/Topic1405467-391-1.aspx</link><description>[quote][b]gsd1 (1/10/2013)[/b][hr]Hi, Why the following code gives error? I have @temp table variable already declared, @p_SampleRecords variable already declared and assigned a value.Declare @strSql varchar(max)set @strSql = 'select top ' + cast(@p_SampleRecords as varchar) + ' * from @temp order by TStamp desc'Exec (@strSql)Thanks &amp; Regards,[/quote]Your dynamic sql runs in a new batch. You think you have @p_SampleRecords variable already declared and assigned a value but that is not in the same batch. From what you posted I don't think you need dynamic sql at all.</description><pubDate>Thu, 10 Jan 2013 07:55:15 GMT</pubDate><dc:creator>Sean Lange</dc:creator></item><item><title>EXEC sql string that has table variable</title><link>http://www.sqlservercentral.com/Forums/Topic1405467-391-1.aspx</link><description>Hi, Why the following code gives error? I have @temp table variable already declared, @p_SampleRecords variable already declared and assigned a value.Declare @strSql varchar(max)set @strSql = 'select top ' + cast(@p_SampleRecords as varchar) + ' * from @temp order by TStamp desc'Exec (@strSql)Thanks &amp; Regards,</description><pubDate>Thu, 10 Jan 2013 07:52:31 GMT</pubDate><dc:creator>gsd1</dc:creator></item></channel></rss>