sql server在字符串中保存exec(@query)的结果

时间:2014-06-05 12:03:05

标签: sql sql-server database

我有一个返回单个结果的查询。

  @query='select name from studtable where id=1'

我应该如何编写查询,以便将结果保存在字符串中,@result包含结果。

  @result=exec(@query)

2 个答案:

答案 0 :(得分:1)

To execute a string, we recommend that you use the sp_executesql stored procedure
instead of the EXECUTE statement. Because this stored procedure supports parameter
substitution, sp_executesql is more versatile than EXECUTE; and because
sp_executesql generates execution plans that are more likely to be reused by SQL
Server, sp_executesql is more efficient than EXECUTE.

在此处阅读更多内容:http://technet.microsoft.com/en-us/library/ms175170(v=sql.105).aspx

所以你可以写成"

DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @IntVariable INT
DECLARE @name varchar(30)
SET @SQLString = N'SELECT @nameOUT = name
                   from studtable where id=@id'
SET @ParmDefinition = N'@id tinyint,
                        @nameOUT varchar(30) OUTPUT'
SET @IntVariable = 1
EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@id = @IntVariable,
@nameOUT=@name OUTPUT
SELECT @name

答案 1 :(得分:0)

您可以执行以下操作,使用带有sp_executesql参数的output来存储结果。从这里观察Assign result of dynamic sql to variable

declare @ret int
set @ret = 0

set @query='select name from studtable where id=1'

exec sp_executesql @query, N'@var int out', @ret out

select @ret