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
 General SQL Server Forums
 New to SQL Server Programming
 Database declare in variable

Author  Topic 

audrius
Starting Member

1 Post

Posted - 2011-09-21 : 03:22:15
DECLARE @LVSAF_AdminDB SYSNAME;
SET @LVSAF_AdminDB = 'CRMTrade_v1_Dev'
"'below near this dot i got error 'incorrect syntax near '.' expected ('"
Select * from @LVSAF_AdminDB.[dbo].[User_Users] where Username like @UserName

I want to declare my database name as variable in this selection, but it say to me that i can't write it in this way.
If i change code to this:
Select * from CRMTrade_v1_Dev.[dbo].[User_Users] where Username like @UserName
everything works just perfectly that how i am expecting. so am i able to declare database as variable and use it for my queries?

Any help is appreciated
Best regards, Audrius

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-21 : 05:38:13
you need to use dynamic sql for this like

DECLARE @Sql varchar(1000)
SET @Sql='Select * from '+ @LVSAF_AdminDB +'.[dbo].[User_Users] where Username like '+ @UserName

EXEC(@sql)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -