Friday, March 9, 2012

I need to select database name from sysdatabases & make dynamic 'u

I am trying to make a dynamic 'use' statement so that some code can loop
through the databases listed in sysdatabases, pull the name and place it into
a variable after the 'use ' keyword. My test code thus far looks like this:
begin
declare @.db_name varchar(200)
declare @.codevarchar(200)
set @.db_name = 'nic_int_ldr'
select @.code = 'use ' + rtrim(ltrim(@.db_name))
print @.code
exec (@.code)
--use nic_int_ldr
select max(id_bat) from ldr_batch
end
At this point I'm just trying to get it to work with a hard coded database
name and I can't even get that to go.
Is it not possible to make a 'use ' statement work this way?
Thanks,
John Miceli
Use is local to a batch, and EXEC is effectively a batch. Put all the thing you want to execute
inside the same EXEC.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"John Miceli, MCDBA" <JohnMiceliMCDBA@.discussions.microsoft.com> wrote in message
news:AA82D9E1-715C-4AE4-B69D-901E989763A5@.microsoft.com...
>I am trying to make a dynamic 'use' statement so that some code can loop
> through the databases listed in sysdatabases, pull the name and place it into
> a variable after the 'use ' keyword. My test code thus far looks like this:
> ----
> begin
> declare @.db_name varchar(200)
> declare @.code varchar(200)
> set @.db_name = 'nic_int_ldr'
> select @.code = 'use ' + rtrim(ltrim(@.db_name))
> print @.code
> exec (@.code)
> --use nic_int_ldr
> select max(id_bat) from ldr_batch
> end
> ----
> At this point I'm just trying to get it to work with a hard coded database
> name and I can't even get that to go.
> Is it not possible to make a 'use ' statement work this way?
> Thanks,
> John Miceli

No comments:

Post a Comment