-- sp_executesql中參數值,要么順序和參數申明中的順序一致,要么指定參數名字
declare @stmt nvarchar(500)
declare @cnt int ;
declare @maxid int
set @stmt = 'select @maxid= cast(max(userid) as int),@count = count(1) from c_user';
-- 1、按聲明順序
execute sp_executesql @stmt,N'@maxid varchar(10) output,@count int output',@maxid output,@cnt output
--2、給定參數名:
execute sp_executesql @stmt,N'@maxid varchar(10) output,@count int output',@count=@cnt output,@maxid=@maxid output
select @cnt as cnt,@maxid as maxid
declare @rq1 datetime = '2024-07-01'
declare @rq2 datetime = '2024-07-31'
declare @busno varchar(10) = ''
declare @sql nvarchar(4000)=''
set @sql = '
select count(1)
from u_sale_c
where accdate >= @rq1 and accdate < dateadd(day,1,@rq2)
'
if @busno <> ''
set @sql += '
and busno = '''+@busno+''''
execute sp_executesql @sql,N'@rq1 datetime,@rq2 datetime',@rq1,@rq2
--select count(1) from u_sale_c where accdate >='2024-07-01' and accdate < '2024-08-01' --242758
--select count(1) from u_sale_c where accdate >='2024-07-01' and accdate < '2024-08-01' and busno ='0001' --6441