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
 Transact-SQL (2000)
 Variable difficulties

Author  Topic 

anderskd
Starting Member

25 Posts

Posted - 2007-02-08 : 18:37:30
Hello,
I've seen this have problems before but I have a question on using variables for tablenames and database names;

Is there anyway to do something like this:
DECLARE @TNAME AS CHAR(12)
SET @TNAME = 'CUSTOMER'
SELECT * FROM @TNAME

Preferably I need to pass in a database name; like this:
DECLARE @DBNAME AS CHAR(12)
SET @DBNAME = 'DB1'
SELECT * FROM @DBNAME..CUSTOMER
--The query should be read as SELECT * FROM DB1..CUSTOMER

Thanks for any help you may provide!





tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2007-02-08 : 18:45:07
Oh brother. Why do you need to do this? This is very, very bad for performance and security reasons.

Why does it need to be dynamic?

Tara Kizer
Go to Top of Page

anderskd
Starting Member

25 Posts

Posted - 2007-02-08 : 18:51:45
I want to make a stored procedure that I can pass in the database and/or table (and possibly even linked server) to collect a bunch of data from about 50 different databases on two different servers.

I can find a way around it, but it keeps coming up from time to time, so it would be great to be able to do it. Messy and poor performance, yup. But that would be fine for my circumstances.

Thanks!

Surfer, Hunter, Fisher, CPA, and Programmer.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2007-02-08 : 19:00:25
Just be warned that this is a very bad idea:
http://www.sqlteam.com/item.asp?ItemID=4599

Tara Kizer
Go to Top of Page

anderskd
Starting Member

25 Posts

Posted - 2007-02-09 : 10:40:18
That makes sense now. Put together the whole statement as a string then use the exec statement to run it.

I'm not too worried about performance. It is just collecting data from a number of sources, probably ran monthly.

Thanks for the help and ideas!

Surfer, Hunter, Fisher, CPA, and Programmer.
Go to Top of Page
   

- Advertisement -