相关文章推荐
爱玩的金鱼  ·  python ...·  1 年前    · 
越狱的刺猬  ·  ConvertFrom-Json ...·  1 年前    · 
刀枪不入的核桃  ·  DBeaver 22.1.1 ...·  1 年前    · 
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

转:http://blog.163.com/zangyunling@126/blog/static/16462450520113212357892/