Question

Is it possible to do something like this:

DECLARE @SourceDB VARCHAR(100);
SET @SourceDB = [DatabaseName]


INSERT INTO CompletedScope
( uidInstanceID ,
  completedScopeID ,
  state ,
  modified
)
SELECT uidInstanceID ,
       completedScopeID ,
       state ,
       modified
FROM SourceDB.[dbo].CompletedScope;

Basically use the declared SourceDB variable in the query.

Was it helpful?

Solution

You will need to use Dynamic sql for this ...

DECLARE @SourceDB NVARCHAR(128), @Sql NVARCHAR(MAX);
SET @SourceDB = 'DatabaseName';


SET @Sql = N'INSERT INTO CompletedScope
                    ( uidInstanceID ,
                      completedScopeID ,
                      state ,
                      modified
                    )
            SELECT uidInstanceID ,
                   completedScopeID ,
                   state ,
                   modified
            FROM ' + QUOTENAME(@SourceDB) + '.[dbo].CompletedScope;'

EXECUTE sp_executesql @Sql

Use QUOTENAME() function when concatenating variables to your sql , protects you against Sql Injection attacks.

OTHER TIPS

You can use a dynamic query

SELECT @sql=
'INSERT INTO CompletedScope
        ( uidInstanceID ,
          completedScopeID ,
          state ,
          modified
        )
SELECT uidInstanceID ,
       completedScopeID ,
       state ,
       modified
FROM ' + @SourceDB + '.[dbo].CompletedScope;'

EXEC sp_executesql @sql
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top