日期:2014-05-17  浏览次数:20492 次

求助~动态语句拼接条件表的条件,并且算出最终的符合条件数
select  * from warning
warningname                condition
年龄大于30岁的人 datediff(year,birthday,getdate())>30
当月过生日的人         month(birthday)=month(getdate())

----------------------
上面这个是条件表,我需要的效果是下图,从person表中查找符合条件的人数
select count(1) from person where + [warning表中的condition]
                                                             符合条件的人数
年龄大于30岁的人 datediff(year,birthday,getdate())>30     2
当月过生日的人         month(birthday)=month(getdate())         1

-------------------------
DECLARE @Sql nvarchar(MAX);
SET @Sql='SELECT *'
select @Sql = @sql + ',(select count(1) from person where ' + condition + ') ' + WarningName from warning
set @sql = @sql + ' from warning'
print @sql
exec(@sql)

试用了动态语句,只能达到这个效果。。求助大神们
                                                              年龄大于30岁的人  当月过生日的人
年龄大于30岁的人 datediff(year,birthday,getdate())>30         2 1
当月过生日的人         month(birthday)=month(getdate())         2 1

------解决方案--------------------


declare @sql nvarchar(max)

select @Sql= 
isnull(@sql+' union all ','')+N'select N'''+
WarningName+''' as [WarningName],''' +
condition + ''' as [condition], count(1) as [人数] from #person where ' + 
condition from #warning
exec(@sql)

是不是这样?