从动态 SQL 获取输出参数值

Obtain output parameter values from dynamic SQL(从动态 SQL 获取输出参数值)
本文介绍了从动态 SQL 获取输出参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

declare @var varchar(max),@course varchar(max)
set @var='ABC'
set @Query=''
set @Query='  
select @course=PARAM from TABLE where PARAM='''+@var+''''
print @Query
exec (@Query)

由于上述查询返回错误为

Since the above query returns an error as

必须声明标量变量@course"

Must declare the scalar variable "@course"

此处的查询是我现在正在遵循的替代方法,以使该查询成功.

The query here is the alternative I am following right now to make that query successful.

declare @var varchar(max),@course varchar(max),@Query varchar(max)
Create table #temp(param1 varchar(max))
set @var='ABC'
set @Query=''
set @Query='insert #temp(param1)
select PARAM from TABLE where PARAM='''+@var+''''
print @Query
exec (@Query)
select @course=param1 from #temp
drop table #temp

除了我上面提到的解决方案之外,还有其他更好的选择吗?

Is there any other better alternative to this other than the solution I have mentioned above?

推荐答案

好吧,我不确定您是否真的需要在这里使用动态 SQL,但我怀疑您为我们简化了一个更复杂的示例.(提示:您不需要这样做.)

Well I'm not sure that you actually need to use dynamic SQL here, but I suspect that you dumbed down a more complex example for us. (Tip: you don't need to do that.)

如果这就是你所做的一切,那为什么不只是:

If this is all you're doing, then why not just:

SELECT @course = PARAM FROM dbo.Table WHERE PARAM = @var;

(这甚至没有意义 - 根据定义,@course@var 要么相等,要么该行不存在.)

(Which doesn't even make sense - by definition @course and @var are either equal or the row doesn't exist.)

如果您的 SQL 实际上更复杂,那么您需要停止使用 EXEC() 并使用 sp_executesql.这允许的一件事是使用强类型参数(包括 OUTPUT)具有更大的灵活性.这是一个简单的例子:

If your SQL is actually more complicated, then you need to STOP using EXEC() and embrace sp_executesql. One of the things this allows is much more flexibility with strongly-typed parameters (including OUTPUT). Here is a quick example:

DECLARE @table_name SYSNAME;

DECLARE @var VARCHAR(MAX), @course VARCHAR(MAX), @sql NVARCHAR(MAX);

SELECT @var = 'ABC', @table_name = N'TABLE_2012';

SET @sql = N'SELECT @course = PARAM FROM ' + @table_name 
  + ' WHERE PARAM = @var;'

EXEC sp_executesql @sql,
  N'@var VARCHAR(MAX),@course VARCHAR(MAX) OUTPUT',
  @var, @course OUTPUT;

PRINT @course;

这篇关于从动态 SQL 获取输出参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)