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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Dynamic SQL and table names

Author  Topic 

psin
Starting Member

1 Post

Posted - 2008-06-05 : 10:49:36
Hi all,

I have been attempting to construct some dynamic SQL using a table name as a parameter, and call it using sp_executesql, in SQL Server 2005.

According to all of the searches and articles I have read today, the following should work:

DECLARE @rownum INT
DECLARE @tabNam NVARCHAR(100)
DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)

SET @rownum = 35
SET @tabNam = 'AdminScriptHistory'

SELECT @SQLString = N'SELECT * FROM @table where executionorder=@row'
SET @ParmDefinition = N'@table VARCHAR(100), @row INT'

EXEC sp_executesql @SQLString, @ParmDefinition, @tabNam,@rownum

However, it fails with:

Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@table".

Anybody know why?

Cheers

jezemine
Master Smack Fu Yak Hacker

2886 Posts

Posted - 2008-06-05 : 11:55:14
http://sommarskog.se/dynamic_sql.html


elsasoft.org
Go to Top of Page
   

- Advertisement -