0

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.

3
  • Did you try? What was the result? Commented Mar 4, 2014 at 18:42
  • 1
    Anytime you need to parameterize on an object name (column, table, database) etc. you need to use dynamic sql Commented Mar 4, 2014 at 18:44
  • You cant use table names like that,you need dynamic sql,put a string into a variable then execute it. Commented Mar 4, 2014 at 18:44

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.