1

Can anybody tell me how i can do this?

declare @test varchar(20)
set @test ='DatabaseName'

select b.* from @test.dbo.Table_Name  

Here i am taking database from variable and using it in query.

Shall do this?

Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
Abhijith Nayak
  • 448
  • 7
  • 21
  • Possible duplicate of http://stackoverflow.com/questions/190776/how-to-have-dynamic-sql-in-mysql-stored-procedure ? Depends if we're talking about MySQL here or not – Tom Mac Sep 30 '11 at 07:31

2 Answers2

1

Make use of Exec command or Sp_executesql because you are building dynamic query.

sp_executesql (Transact-SQL)

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1
declare @test varchar(20)
set @test ='DatabaseName'

declare @SQL nvarchar(max)
set @SQL = 'select b.* from '+quotename(@test)+'.dbo.Table_Name as b'

exec (@SQL)
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
  • @AbhijithNayak "Returns a Unicode string with the delimiters added to make the input string a valid SQL Server delimited identifier" http://msdn.microsoft.com/en-us/library/ms176114.aspx – Mikael Eriksson Sep 30 '11 at 08:43
  • @AbhijithNayak "you can use quotename() to protect yourself against SQL injection" http://www.sommarskog.se/dynamic_sql.html#quotestring – Mikael Eriksson Sep 30 '11 at 08:44