March 20, 2014 at 4:12 am
A quick one for any T-SQL Gurus out there.
I need this to always run in a user db.
How do I get the use section to work properly. In fact at all.
declare @dbname varchar(100)
set @dbname = (select name from sys.databases where database_id in (select MAX(database_id) from sys.databases where database_id> 5))
print @dbname
Use [+'@dbname'+]
go
March 20, 2014 at 5:10 am
Hi,
I think you need to do the whole statement in dynamic SQL. Something like (in addition to what you have):
DECLARE @sSQL NVARCHAR(MAX);
SET @sSQL = 'USE [ + @dbName + ']';
EXEC sp_executesql @sSQL;
March 20, 2014 at 5:40 am
Here's another approach that doesn't rely on dynamic SQL:
declare @dbname sysname;
select top 1 @dbname = name
from sys.databases
where database_id > 5
order by database_id desc;
select @dbname;
March 20, 2014 at 6:04 am
Worked.. Excellent!!! Thanks
March 20, 2014 at 7:08 am
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy