Passing down dbname as parameter in stored proc

I have a collection of stored procedures that I use for data migration purposes. I have to run this collection of procs on a number of different databases, so what I would like is to be able to pass the database name into each proc, instead of retyping each of them. or having different copies of the procedures about the place.

i.e each statement contains the reference to the DB (INSERT INTO DATABASENAME.dbo.TABLENAME)

Ideally, some sort of global variable would be good - that I could refer to in each stored proc, and then just pass it down to them all in an overarching proc.

Can this be done? and how does the syntax look when referring to it - is it @databasevar.dbo.TABLENAME - or do I need to create it all as one string, and then execuite the string.

Thanks,

Jamie
j_young_80Asked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Connect With a Mentor Billing EngineerCommented:
as dtodd indicates, the "short" version will be dynamic sql (see code snippet).
however, I do agree that it is not the "best" method in terms of security ...

note: whenever inside the @sql = ' ... ' you need to put a single quote, you will have to duplicate it: @sql = '  insert into yourtable values ('mc''afeee ') '
CREATE PROCEUDRE do_work (@dbname sysname)
AS
DECLARE @sql varchar(2000)
set @sql = 'USE [' + @dbname + '
  INSERT INTO ... 
 '
EXEC (@sql)

Open in new window

0
 
David ToddSenior DBACommented:
Hi,

afaik you will need to create a string in the procedure, and dynamically execute that string.

Dynamic SQL is less secure than normal SQL.

Cheers
  David
0
 
j_young_80Author Commented:
So is there a concept of a global variable in stored procs? something like the @@ identity?

Also - the line you have listed;

CREATE PROCEUDRE do_work (@dbname sysname) - is this passing a type of sysname into the proc? wouldn't this just be a string?

Agreed on the security side of things - but in this instance it's probably not a huge issue - I had hoped there would be a more elegant solution than building up strings however.
0
 
David ToddConnect With a Mentor Senior DBACommented:
Hi,

iirc sysname in SQL 2000 is close to varchar( 128 ). So yes it is just a string. But sysname is strictly correct, and I use it as a type in this sort of situation myself.

HTH
  David
0
All Courses

From novice to tech pro — start learning today.