【问题标题】:How can I get the query result which includes IF ELSE when using pymssql on SQL Server?在 SQL Server 上使用 pymssql 时如何获取包含 IF ELSE 的查询结果?
【发布时间】:2019-08-29 01:28:53
【问题描述】:

我在 python 应用程序中使用pymssql 连接到 SQL Server 数据库。我有一个查询语句定义如下:

DECLARE @type int
SELECT @type = type FROM myTable WHERE id = 1000

IF @type >= 700
    SELECT 1
ELSE
    SELECT 0

当我在 SQL Server 中运行上述 sql 时,我可以获得 10 的输出,这取决于行的 type 值。但是当我在 python 中运行代码时,它总是返回None:

cursor.execute(sql)  # sql is the above select statement
cursor.fetchone()  # this line return None

我期望得到值 1 或 0,我怎样才能在 pymssql 中实现它?

【问题讨论】:

  • 我不确定您是否可以在 SQL Server 之外或在存储过程之外运行像这样的动态 SQL。

标签: python sql-server pymssql


【解决方案1】:

将您的代码更新为此。 type 是 sql server 中的保留关键字。添加了TOP 1 以确保我们只会得到[type] 的1 个结果。

DECLARE @type int
SET @type = 0
SELECT TOP 1 @type = [type] FROM myTable WHERE id = 1000

IF @type >= 700
    SELECT 1
ELSE
    SELECT 0

【讨论】:

  • 它有效,我可以看到结果。您能否再解释一下为什么在 select 语句中添加TOP 1
  • 添加了TOP 1 以确保我们只会得到[type] 的1 个结果。
  • 但是如果它没有返回1个结果,我会得到0作为返回值,对吧?
  • 不,您需要在选择之前添加 SET @type = 0
  • 如果选择返回超过 1 行,if 语句会抛出异常?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
相关资源
最近更新 更多