从pymssql中的存储过程返回第一个表后,无法获取列名

时间:2017-12-27 11:47:39

标签: python pymssql columnname

我在sql server中有一个返回多个表的过程:

create procedure newtest
as 
begin
   select 1 as a
   select 2 as b
end

在python中,cursor.description只返回第一个列名:a

我想获取每个表中的每个列名。

我该怎么做?

这是我的代码:

cur.execute(com)
                num_tables=0
                while True:
                    print(cur.description)
                    ret=cur.fetchall()   

                    if len(ret)>0: 
                        ret_list.append(ret)
                        num_tables+=1
                        print(ret)                       
                    else:
                        break

1 个答案:

答案 0 :(得分:3)

如果命令返回多个表(即多个结果集)。您可以使用Cursor.nextset()从一组切换到下一组。

类似的东西:

num_tables = 0
while True:
    print(cur.description)

    # all lines of the current set
    ret = cur.fetchall()

    if len(ret) > 0:
        ret_list.append(ret)
        num_tables += 1
        print(ret)

    # check and fetch the next set
    if not cur.nextset():
        break

不强制结果集具有相同的列数。例如:

create procedure newtest
as 
begin
   select 1 as a
   select 2 as b, 3 as c
end

结果是:

(('a', <class 'int'>, None, 10, 10, 0, False),)
[(1, )]
(('b', <class 'int'>, None, 10, 10, 0, False), ('c', <class 'int'>, None, 10, 10, 0, False))
[(2, 3)]
相关问题