执行动态SQL语句的函数怎么写
其实你这你都知道用函数实现不了的,因为你的输入参数@SQL是动态的,那必须用exec执行,而函数里不能用exec。建议你用存储过程实现,示例如下:
创建存储过程:
create procedure TEST
(
@SQL NVARCHAR(200),
@RE INT output
)
AS
BEGIN
set nocount on
if exists (select * from tempdb.dbo.sysobjects where xtype='U' and id=object_id('#test'))
drop table #test
create table #test(total int)
insert into #test
exec (@SQL)
select @RE=isnull(total,0) from #test
set nocount off
END
调用示例:
declare @RE int
exec TEST 'select 1+1',@RE output
PRINT @RE
结果:
2