declare @tableName nvarchar(50)
set @tableName=case
when @IDType='CustomerID' then 'Customer'
when @IDType='EventRegistrationID' then 'EventRegistration'
when @IDType='CustomerServiceID' then 'CustomerService'
when @IDType='ReservationID' then 'Reservation'
when @IDType='PartnerID' then 'Partner'
when @IDType='LocationID' then 'Location'
else 'LocationService'
end
declare @sqlstr nvarchar(500)
set @sqlstr='select @Count=count(*) from '+@tableName+ ' where '+@IDType+'='+cast(@TestID as char);
exec sp_executesql @sqlstr,N'@Count int output',@Count output
如果有参数的话,在执行这个字符串时,将参数加在后面,例如:@Count
本文介绍了一个使用T-SQL动态执行查询的案例。通过设置变量@tableName和@sqlstr,构造了针对不同ID类型的SQL查询语句,并利用sp_executesql存储过程执行这些动态生成的SQL语句。
3943

被折叠的 条评论
为什么被折叠?



