2011-05-04 123 views
0

有谁知道如何在SQL Server中执行SQL查询后输出SQL查询吗?SQL Server:打印生成的SQL查询

select count(eo.equal_opps_id) as 'Age 40 - 49' 
from dbo.app_equal_opps eo, dbo.app_status s 
where eo.date_of_birth > DateAdd(yy,-49,getDate()) 
and eo.date_of_birth < DateAdd(yy,-39,getDate()) 
and eo.application_id = s.status_id 
and s.job_reference_number = '33211016' 
and s.submitted = 1  

上面显示了一个SQL查询,但是,一旦它被执行,我想看到所创建的实际日期值在下面的章节

DateAdd(yy,-49,getDate()) 
DateAdd(yy,-39,getDate()) 

换句话说,一旦查询执行的,我可以打印SQL查询输出,使其显示像这样

select count(eo.equal_opps_id) as 'Age 40 - 49' 
from dbo.app_equal_opps eo, dbo.app_status s 
where eo.date_of_birth > '1962-05-04 13:00:00.000' 
and eo.date_of_birth < '1972-05-04 13:00:00.000' 
and eo.application_id = s.status_id 
and s.job_reference_number = '33211016' 
and s.submitted = 1 

与往常一样,任何反馈将不胜感激。

谢谢大家。

+0

它不会以文本形式展开这些函数调用 - 您显示的“生成”形式将永远不会存在。 – 2011-05-04 14:49:00

回答

2

两个日期添加到您的选择列表:

select 
    count(eo.equal_opps_id) as 'Age 40 - 49' 
    ,DateAdd(yy,-49,getDate()) as LesserDate 
    ,DateAdd(yy,-39,getDate()) as GreaterDate 
from 
    dbo.app_equal_opps eo, dbo.app_status s 
where 
    eo.date_of_birth > DateAdd(yy,-49,getDate()) 
    and eo.date_of_birth < DateAdd(yy,-39,getDate()) 
    and eo.application_id = s.status_id 
    and s.job_reference_number = '33211016' 
    and s.submitted = 1 
0

我能想到的唯一办法是凌乱。你可以将sql构建为一个字符串,然后使用构建函数中的exec来执行它。

declare @sql as varchar(max) 

select @sql = ' 
select count(eo.equal_opps_id) as ''Age 40 - 49'' 
from dbo.app_equal_opps eo, dbo.app_status s 
where eo.date_of_birth > ' + (select cast(DateAdd(yy,-49,getDate()) as varchar(100))) + ' 
and eo.date_of_birth < ' + (select cast(DateAdd(yy,-39,getDate()) as varchar(100))) + ' 
and eo.application_id = s.status_id 
and s.job_reference_number = ''33211016'' 
and s.submitted = 1' 

print @sql 
exec(@sql)