SQL Table "Pointer"?
Using SQl Server 2000 I have a stored procedure that joins 2 tables and then returns the data. I want this sp to be able to do this for whatever table name I pass into it, otherwise I'll have the exact same code with the exception of the table name 20 or so times in a giant if开发者_JS百科 statement. Basically, how do I use a variable to point to a table, or is that allowed? Thanks.
You need dynamic SQL, start here The Curse and Blessings of Dynamic SQL to learn how to do it correctly so that nobody drops your tables or does anything else possible with SQL Injection
Try building the SELECT as a string and then calling EXEC and passing the string.
e.g.
declare @sql varchar(500)
set @sql = 'select whatever from ' + @tableName
exec @sql
One proc to do anything is usually a bad bad idea. 20 possible tables I might need to go to depending on the circumstances almost always indicates a database design that is bad. Read the article Denis posted on the curses and blessings of dynamic SQL.
精彩评论