DECLARE @DatabaseName NVARCHAR(max); SET @DatabaseName = 'MainDb'
USE @DatabaseName
Wouldn’t work. How to make it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’d have to use dynamic SQL if you want to do it dynamically like that. Would mean anything you want to execute under the context of that DB, you’d need to include in the dynamic SQL statement too.
i.e. assume you want to list all the tables in MainDB:
This won’t work, as the USE statement is in a different context – once that EXECUTE has run, the following SELECT will NOT be running in that same context and so won’t be running in MainDb (unless the connection was already set to MainDb)
So you’d need to do:
Of course, you need to be very careful with SQL injection, for which I point you to the link in Barry’s answer.
To prevent SQL Injection, you could also use QUOTENAME() function, it wraps parameter in square brackets: