Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql use statement with variable

I'm trying to switch the current database with a SQL statement. I have tried the following, but all attempts failed:

  1. USE @DatabaseName
  2. EXEC sp_sqlexec @Sql -- where @Sql = 'USE [' + @DatabaseName + ']'

To add a little more detail.

EDIT: I would like to perform several things on two separate database, where both are configured with a variable. Something like this:

USE Database1 SELECT * FROM Table1  USE Database2 SELECT * FROM Table2 
like image 649
Drejc Avatar asked Jun 24 '09 08:06

Drejc


People also ask

Can I use a variable in an SQL statement?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

How do I add a variable to an SQL statement?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

How do you set a SELECT statement to a variable in SQL?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

How do I use a variable in an in clause SQL Server?

You can't use a variable in an IN clause - you need to use dynamic SQL, or use a function (TSQL or CLR) to convert the list of values into a table.


2 Answers

The problem with the former is that what you're doing is USE 'myDB' rather than USE myDB. you're passing a string; but USE is looking for an explicit reference.

The latter example works for me.

declare @sql varchar(20) select @sql = 'USE myDb' EXEC sp_sqlexec @Sql  -- also works select @sql = 'USE [myDb]' EXEC sp_sqlexec @Sql 
like image 98
Joel Goodwin Avatar answered Oct 03 '22 20:10

Joel Goodwin


   exec sp_execsql @Sql 

The DB change only lasts for the time to complete @sql

http://blog.sqlauthority.com/2007/07/02/sql-server-2005-comparison-sp_executesql-vs-executeexec/

like image 36
Preet Sangha Avatar answered Oct 03 '22 21:10

Preet Sangha