日期:2014-05-18  浏览次数:20532 次

一个菜鸟问题
问一个菜鸟问题,变量替换数据库名称行不通,可否解决?

declare @name char(20)
set @name='master'
select * from @name.sys.objects

/* Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '.'. */

------解决方案--------------------
SQL code

declare @name char(20)
set @name='master'
exec('select * from '+@name+'.sys.objects')

------解决方案--------------------
SQL code
declare @name char(20)
set @name='master'
exec('select * from '+@name+'.sys.objects')

------解决方案--------------------
SQL code

declare @name char(20)
set @name='master'
exec('select * from '+@name+'.sys.objects')

--都是山寨我的,哼哼哼[img=http://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/003/onion/5.gif][/img]

------解决方案--------------------
SQL code

declare @name char(20)
set @name='master'
exec('select '''+@name+''',max(create_date) from '+@name+'.sys.objects')

                     
-------------------- -----------------------
master               2012-03-31 11:34:07.700

(1 row(s) affected)