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
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):
I suggest reading the linked article – it is a comprehensive treatment of the subject of dynamic SQL.