I can assign database name from the variable in T-SQL MS SQL 2005 ?

Is there any way I can assign database name from the variable in T-SQL ?
What other alernative ?
My code look like this
SET @dbRS = 'RS' + LTRIM(RTRIM(@StoreID)) --Database Name

if NOT EXISTS(SELECT * FROM sys.databases WHERE NAME = @dbRS)
      EXEC sp_attach_db @dbname = @dbRS,
      @filename1 = @dbFilePath,
      @filename2 = @dbLogFilePath
      --HERE @dbRS variable contain the attached database name
      -- I Want to run this in a loop and update all the databases finds in the table
                     -- Which ofcourse have the same table structures
                    Update  @dbRS..Customer
      Set @dbRS..Customer.CustomerName = btr..Customer.CustomerName
      FROM @dbRS.Customer JOIN BTR..Customer
      ON @dbRS..Customer.CustomerID= btr..Customer.CustomerID
kghiAsked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Connect With a Mentor Billing EngineerCommented:
only with dynamic sql:
SET @dbRS = 'RS' + LTRIM(RTRIM(@StoreID)) --Database Name 
if NOT EXISTS(SELECT * FROM sys.databases WHERE NAME = @dbRS)
      EXEC sp_attach_db @dbname = @dbRS, 
      @filename1 = @dbFilePath, 
      @filename2 = @dbLogFilePath 
 DECLARE @sql VARCHAR(MAX)
 SET @SQL = '
     Update c
      Set CustomerName = b.CustomerName
      FROM [' + @dbRS + '] Customer c
      JOIN BTR..Customer b
      ON c.CustomerID= b.CustomerID
  '
  EXEC(@SQL)
 

Open in new window

0
 
kghiAuthor Commented:
Thanks angellll !
It worked!
0
All Courses

From novice to tech pro — start learning today.