3

Today I get my database name like that :

set @databaseNameTXT = 'NewStat1DB';

And then I insert the data to the right table like that:

IF @databaseNameTXT = 'NewStat1DB' 
    BEGIN
        INSERT INTO [NewStat1DB] (wStat_id) values(@wStat_id)
    END

IF @databaseNameTXT = 'NewStat2DB'
    BEGIN
        INSERT INTO [NewStat2DB] (wStat_id) values(@wStat_id)
    END

How can I use the variable inside the t-sql and run it, something like:

INSERT INTO [@databaseNameTXT] (wStat_id) values(@wStat_id)

Thanks

2 Answers 2

4

You need to use dynamic SQL for this, though you need to be careful of SQL Injection.

Database, schema, table and column names cannot be variables - the only way to do this is use dynamic SQL.

For example (this is vulnerable to SQL Injection):

sp_executesql 'INSERT INTO [' + @databaseNameTXT + 
                '] (wStat_id) values(' + @wStat_id + ');';

I suggest reading the linked article - it is a comprehensive treatment of the subject of dynamic SQL.

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

5 Comments

This is prone to SQL injection and should not be used.
If you are trying to send in a table name dynamically, there is close to a 100% chance that you have a poor design.
SQL injection attacks are not a factor in every use case. If he's not getting data from a publicly accessible source, it doesn't really matter. For example, he could be doing back-end update with a script that the SQL server agent runs or that he runs manually.
@Jim You think attacks only come from the public? You don't think a script can be hacked? I never trust external data even if it came from from my own code.
No, I think you're being silly and paranoid by telling someone not to use a great tool without knowing the situation in which they would be using it.
1

You can use Dynamic SQL for this:

declare @query nvarchar(max)

set @query = 'INSERT INTO ' + QUOTENAME(@databaseNameTXT) + '(wStat_id) 
                values('+@wStat_id+')'

exec(@query)

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.