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 2000 Forums
 SQL Server Development (2000)
 Parameter in FROM clause

Author  Topic 

ddasilva99
Starting Member

26 Posts

Posted - 2006-10-12 : 11:11:15
Im trying to create a stored procedure where the "FROM" clause is dynamic. I want the FROM clause to be whatever table is passed in from a parameter. For some reason my code doesnt like a parameter in the FROM clause. How do I get this to work?

For example:

ALTER PROCEDURE d6661a03.AuthenticateStudent
@userName VARCHAR(50),
@tableName VARCHAR(50)
AS
SELECT id, name, enabled, password
FROM @tableName
Where username = @userName

nr
SQLTeam MVY

12543 Posts

Posted - 2006-10-12 : 11:16:09
exec ('SELECT id, name, enabled, password
FROM ' + @tableName + '
Where username = ''' + @userName + '''')

Not a good idea though.

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

ddasilva99
Starting Member

26 Posts

Posted - 2006-10-12 : 13:22:23
Why isnt this a good idea?
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-10-13 : 10:14:08
quote:
Originally posted by ddasilva99

Why isnt this a good idea?


Read this
http://www.sommarskog.se/dynamic_sql.html


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -