这是使用动态Sql的人都会碰到这样的问题,需要从动态执行的sql中返回值,下面给一个简单的实现例子。
IF EXISTS(SELECT * FROM SYSOBJECTS WHERE NAME = 'ValueFromSql')
DROP PROC ValueFromSql
GO
create proc ValueFromSql
as begin
declare @value varchar(100)
exec sp_executesql N'select @value=''From Sql'' ',N'@value varchar(100) out ',@value out
print @value
end
DROP PROC ValueFromSql
GO
create proc ValueFromSql
as begin
declare @value varchar(100)
exec sp_executesql N'select @value=''From Sql'' ',N'@value varchar(100) out ',@value out
print @value
end
执行结果为; From Sql
如果想把sql语句当成变量传入,定义应该如下,注意@sql的类型应该是nvarchar
IF EXISTS(SELECT * FROM SYSOBJECTS WHERE NAME = 'ValueFromSql')
DROP PROC ValueFromSql
GO
create proc ValueFromSql
as begin
declare @value varchar(100)
declare @sql nvarchar(4000)
set @sql='select @value=''From Sql'' '
exec sp_executesql @sql,N'@value varchar(100) out ',@value out
print @value
end
DROP PROC ValueFromSql
GO
create proc ValueFromSql
as begin
declare @value varchar(100)
declare @sql nvarchar(4000)
set @sql='select @value=''From Sql'' '
exec sp_executesql @sql,N'@value varchar(100) out ',@value out
print @value
end