2011-05-04 126 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)