【问题标题】:Can't query and put data inside a cursor when using variable inside the query在查询中使用变量时无法查询并将数据放入游标中
【发布时间】:2020-07-10 08:11:03
【问题描述】:

我必须将查询的结果(单列和值被提取)放入变量中。我正在尝试使用游标,但是我根据变量选择要查询的数据库,这是我的查询

SELECT productName, price FROM @ShopName.dbo.Products WHERE ProductName = @ProductName

@ShopName 变量首先从数据库中提取并使用游标分配给变量。 @ProductName 变量由来自 API 的输入参数填充。我必须从特定数据库中获取 ProductName(有多个数据库包含产品),但上面的查询会引发语法错误。此外,当我尝试分配给变量的临时查询时:

SET @Sql = N'SELECT productName, price FROM ' + QUOTENAME(@ShopName) + '.dbo.Products WHERE ProductName = ' + @ProductName

它不允许使用它

DECLARE cursorT CURSOR
FOR
@Sql

这会抛出Incorrect syntax near '@Sql', Expecting '(', SELECT, or WITH

有没有什么方法可以在使用带有数据库名称的变量时在游标中使用该查询?

【问题讨论】:

  • 如果你使用的是动态SQL,你必须全部在动态SQL中完成,不能混用。因此,您还需要在动态 SQL 中运行游标。
  • 其中哪一部分需要使用光标?
  • 除非@ShopName 是表变量,否则您调用...FROM @ShopName... 是没有意义的?请提供完整代码而不是部分代码?

标签: sql-server tsql database-cursor


【解决方案1】:

光标应该在你的技术包的底部,仅在必要时谨慎使用。我不知道在你的情况下是否有必要,没有足够的代码知道。但我想在继续之前把它说出来。

作为纯粹的学术兴趣点,是的,有一些方法可以做到这一点。两种主要方式:

  1. 按照 Dale 的建议,在动态 SQL 中声明一个游标。如果游标是全局的,您仍然可以在声明之后的静态代码中使用游标。
  2. 使用动态 SQL 将结果放入动态 sql 范围之外的内容中,例如临时表。光标在临时表上。

1 很糟糕。这很可能导致将来极难理解的代码。我只是出于好奇而将其包括在内。 2是合理的。

例子:

-- some dummy schema and data to work with
create table t(i int); 
insert t values(1), (2);

-- option 1: declare a cursor dynamically, use it statically (don't do this)

declare @i int;
exec sp_executesql N'declare c cursor global for select i from t';
open c;
fetch next from c into @i;
while (@@fetch_status = 0) 
begin
    print @i;
    fetch next from c into @i;
end
close c;
deallocate c;

-- option 2: dynamically dump data to a table, eg a temp table

create table #u(i int);
exec sp_executesql N'insert #u (i) select i from t';
declare c cursor local for select i from #u;
declare @i int;
open c;
fetch next from c into @i;
while (@@fetch_status = 0) 
begin
    print @i;
    fetch next from c into @i;
end
close c;
deallocate c;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    相关资源
    最近更新 更多