sqlserver中sp_executesql使用实例(获取动态sql输出结果)
语法
sp_executesql [ @stmt = ] stmt [ {, [@params=] N'@parameter_name data_type [ [ OUT [ PUT ][,...n]' } {, [ @param1 = ] 'value1' [ ,...n ] } ]
用法实例
1、获取一个输出结果
使用output获取输出结果的值
declare @num int,
@sqls nvarchar(4000)
set @sqls='select @a=count(*) from customer '
exec sp_executesql @sqls,N'@a int output',@num output
select @num
2、两个输出结果
declare @num int, @sqls nvarchar(4000) ,@sname char(10)
set @sqls='select @a=sno,@b=sname from aa '
exec sp_executesql @sqls,N'@a int output,@b char(10) output',@num output,@sname output
select @num
select @sname
3、输入参数
DECLARE @TableName VARCHAR(50),@sql NVARCHAR(MAX),@OID INT;
SET @TableName = 'aa ';
SET @OID = 1;
SET @sql = 'SELECT * FROM '+QUOTENAME(@TableName) + ' WHERE sno ='+ cast(@OID as char(10)) ;
exec sp_executesql @sql
对于输入参数也可以直接写到语句里面
DECLARE @TableName VARCHAR(50),@sql NVARCHAR(MAX),@OID INT;
SET @TableName = 'aa ';
SET @OID = 1;
SET @sql = 'SELECT * FROM '+QUOTENAME(@TableName) + ' WHERE sno =@oid'
exec sp_executesql @stmt= @sql,
@params = N'@OID AS INT ',
@OID = @OID
或
DECLARE @TableName VARCHAR(50),@sql NVARCHAR(MAX),@OID INT;
SET @TableName = 'aa ';
SET @OID = 1;
SET @sql = 'SELECT * FROM '+QUOTENAME(@TableName) + ' WHERE sno =@oid'
exec sp_executesql @sql, N'@OID AS INT ', @OID