all groups > sql server connect > august 2006 >
You're in the

sql server connect

group:

Using a variable to access a database



Using a variable to access a database J_Jones
8/29/2006 11:04:02 AM
sql server connect: I would like to be able to perform a query
where the database to query is a parameter.
Can this be accomplished? I have tried various methods but none seem to work.

Re: Using a variable to access a database Arnie Rowland
8/29/2006 11:19:52 AM
You will need to use dynamic SQL. See Erlund's article at:

Dynamic SQL
http://www.sommarskog.se/dynamic_sql.html


--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc


Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous


[quoted text, click to view]

Re: Using a variable to access a database Hari Prasad
8/29/2006 7:52:31 PM
Hi,

You need to use dynamic SQL execution either using EXEC or sp_executesql

Some thing like:-

declare @sql varchar(100)
declare @db varchar (10)
set @db='DBNAME'
set @sql ='select * from [ '+@db+'].dbo.tablename'
print @sql
exec(@sql)

Thanks
Hari
SQL Server MVP


[quoted text, click to view]

AddThis Social Bookmark Button