SQL Server:打印生成的SQL查询

时间:2011-05-04 14:33:16

标签: sql sql-server

有没有人知道如何在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 Query输出,以便显示类似这样的内容

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

与往常一样,任何反馈都会非常感激。

谢谢大家。

2 个答案:

答案 0 :(得分: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 

答案 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)