存储过程中拼写sql并执行

直接上代码吧,根据不同的条件拼写sql后并执行

复制代码

ALTER PROCEDURE [dbo].[usp_Statistic_WJB_DZSK_ZT]
(
    @year int,
    @half int,--0表示全年,1表示上半年,2下半年
    @isAll int --0表示只统计党政干部人员,1表示统计全部
)
as
declare @sql    nvarchar(4000)

set @sql=N'select id from 
chgrwpj
where id in(select distinct parentid from chgrymd'
if(@isAll=0)
set @sql=@sql + N' where ((unitcode between ''A0000'' and ''A0025'') or (unitcode between ''B0041'' and ''B0044'') or unitcode=''A1206'' or unitcode=''B0003'' or unitcode=''B0017'' or unitcode=''B0034'' or (unitcode=''B0045'' and positionLevel<=6 and positionLevel>0 and positionname<>''验船师''))'
set @sql=@sql + N') and innerAmount<chgrsh and year(enddate)=@year'
if(@half=1)
set @sql=@sql + N' and month(enddate) between 1 and 6 '
else if(@half=2)
set @sql=@sql + N' and month(enddate) between 7 and 12'

set @sql=@sql + N' order by senddate asc'
exec sp_executesql @sql,
N'@year int,@half int',@year,@half

RETURN
复制代码

 

posted @   爱生活,爱代码  阅读(1186)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示