Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Database variable in SQL Server 2008?

Posted on 2010-11-25
11
Medium Priority
?
612 Views
Last Modified: 2012-05-10
In SQL Server 2008 (Express), I have a stored procedure that includes something like this

    SELECT * FROM DatabaseA.dbo.Table

I want to be able to do this instead

    SELECT * FROM @MyDB.dbo.Table

where @MyDB is a parameter or a variable whose value is DatabaseA

I know I can use Dynamic SQL to construct the select statement as a string and then execute the string. But that strikes me as a kludge and in any event is pretty awkward when I try to take a large procedure and generalize it to operate on a database that's selected at run time.

So, any way to do that? I know SQL Server 2008 has the notion of a table variable but I haven't seen anything that corresponds to a database variable. Any ideas?
0
Comment
Question by:BlearyEye
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
11 Comments
 
LVL 143

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 400 total points
ID: 34213806
you cannot use a variable for a database name...
and yes, you are limited to use a sql string to execute it.
0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 34213848
As angel has pointed out, you cann't do that.  Dynamic SQL is the way.  The only alternative, which is still dynamic SQL so it's not really, but more a different way of doing it.


declare @MyDB sysname, @SQL nvarchar(max), @sp_executesql sysname

set @MyDB = 'SOMEDB'
set @SQL = 'select f1,f2,f3 from dbo.TableA'
set @sp_executesql = quotename(@MyDB) + '.dbo.sp_executesql'

exec @sp_ExecuteSQL @SQL
0
 
LVL 1

Author Comment

by:BlearyEye
ID: 34219017
BrandonGalderisi: your code works, but I haven't been able to figure out why. Articles I've seen on sp_executesql don't use that syntax. Can you give me a pointer to an explanation?
0
Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 34231628
I am assigning @MyDB + '.dbo.sp_executesql' as the procedure to execute.  Perhaps my variable name has made it more confusing.


Maybe:

declare @MyDB sysname, @SQL nvarchar(max), @DYNAMICPROCEDURENAME sysname

set @MyDB = 'SOMEDB'
set @SQL = 'select f1,f2,f3 from dbo.TableA'
set @DYNAMICPROCEDURENAME= quotename(@MyDB) + '.dbo.sp_executesql'

exec @DYNAMICPROCEDURENAME @SQL
0
 
LVL 1

Author Comment

by:BlearyEye
ID: 34235616
That wasn't really my issue. The exec, after unbundling the variables, is
   exec 'SOMEDB'.dbo.sp_executesql  'select f1, f2, f3 from dbo.TableA'

I don't understand the syntax and don't see how this becomes in effect
   select f1, f2, f3 from SOMEDB.dbo.TableA

0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 34235734
Becaue it excutes the "select f1,f2,f3 from dbo.TableA" in SOMEDB because that's how the sp_executesql command was built.
0
 
LVL 1

Author Comment

by:BlearyEye
ID: 34240110
I had looked for doc on sp_executesql (including specifically MSDN) and hadn't found anything that explicitly describes that usage. However, inferring from examples I've seen, it seems to be similar to the USE statement.

This would handle the original question I asked. However, I also need to paramaterize for two databases, with something like the following that copies the data from a table in DbB into the corresponding table in DbA.

   INSERT INTO DbA.dbo.CalibrationData SELECT * FROM DbB.dbo.CalibrationData

Should I use explicit parameters with sp_executesql?
0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 34240358
There is no way to do that without putting one DB name into the @SQL.

This is not some magic syntax specific to sp_executesql.  You can do it with any procedure.


Ex.

declare @FooProc sysname
set @FooProc = 'up_DoFoo'
exec @FooProc
0
 
LVL 39

Expert Comment

by:BrandonGalderisi
ID: 34240372
This is one of those situations where the correct answer is "you can't do that".  And in this case you must use Dynamic SQL.  Even using a variable for the @sp_executesql or @DYNAMICPROCEDURENAME is dynamic SQL.
0
 
LVL 1

Author Comment

by:BlearyEye
ID: 34259212
So, I take the answer to be:

- Dynamic SQL is required
- Parameters for substituting database names are required if more than one database is involved.

If that's right, I'll close this question.
0
 
LVL 39

Accepted Solution

by:
BrandonGalderisi earned 1600 total points
ID: 34259478
Dynamic SQL is required:
Absolutely.  Even what I am doing is dynamic SQL.

Parameters for substituting database names are required if more than one database is involved:
If you want to reference another database, that name must be referenced in the executed SQL.  That reference may not be in the form of a variable, rather it must be part of the executed string.  Building the string by using the value of a variable in the place of a DB name does that.

So, yes.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is basically a blog post I wrote recently. I've found that SARGability is poorly understood, and since many people don't read blogs, I figured I'd post it here as an article. SARGable is an adjective in SQL that means that an item can be fou…
There have been several questions about Large Transaction Log Files in SQL Server 2008, and how to get rid of them when disk space has become critical. This article will explain how to disable full recovery and implement simple recovery that carries…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question