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

使用exec 和union的问题
使用exec   和union的问题
不知为何,如果我使用普通的语句比如:
select   count(*)      
from   tel   where   serv_state   like ' 'F1R ' '
union
select   count(*)      
from   tel   where   serv_state   like ' 'F1N ' '

就可以正常的出现我想要的结果,而且两个结果都是在同一张表上,那么也就是
我可以把两个结果一同复制下来,粘贴在电子表格上,如果,我要union   很多
个结果的话,这样就很方便了。
-----------------------------------
但是,如果我用这样的句子
DECLARE   @TABLENAME   NVARCHAR(100)    
SET   @TABLENAME   =   'tel '
EXEC( 'select   count(*)      
from   [ '   +   @TABLENAME   +   ']   where   serv_state= ' 'F1R ' ' ')
union
EXEC( 'select   count(*)      
from   [ '   +   @TABLENAME   +   ']   where   serv_state= ' 'F1N ' ' ')

则会出现『在关键字   'union '   附近有语法错误』的提示
如果上面的代码中,我把union   去掉,虽然也可显示两条记录,但结果却是分别
在两张表里面,这样就不利于我复制,粘贴,所以,请问,有什么办法,使用第
二段那样有exec   的代码中,又可使用union   ,将几条不同的记录给何在同一
个表格中显示出来?


------解决方案--------------------
--把union 放在exec()中

DECLARE @TABLENAME NVARCHAR(100)

SET @TABLENAME = 'tel '

EXEC( 'select count(*)
from [ ' + @TABLENAME + '] where serv_state= ' 'F1R ' '
union
select count(*)
from [ ' + @TABLENAME + '] where serv_state= ' 'F1N ' ' ')